【发布时间】:2012-09-28 17:13:36
【问题描述】:
我有一个 UIViewController 类,我试图在其中分配一个 UIButton 类。这是一个示例代码。
MyViewController.m
- (void)viewDidLoad
{
CGRect frame = CGRectMake(companybuttonxOffset, companybuttonyOffset, buttonWidth, buttonHeight);
CustomButton *customButton = [[CustomButton alloc]initWithFrame:frame];
[self.view addSubview:customButton];
[super viewDidLoad];
}
CustomButton.h
#import <UIKit/UIKit.h>
@interface CustomButton : UIButton {
}
@property (nonatomic, assign) NSInteger toggle;
- (void)buttonPressed: (id)sender;
@end
CustomButton.m
#import "CustomButton.h"
@implementation CustomButton
@synthesize toggle;
- (id) initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
//custom button code
[self addTarget: self action: @selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];
}
return self;
}
- (void)buttonPressed: (id)sender
{
NSLog(@"buttonPressed !!!!!");
}
@end
虽然按钮存在于我的视图控制器中,但如果我按下按钮,我会不断收到此错误 - -[UIButton buttonPressed:]: unrecognized selector sent to instance 0xb1dca50
根据我在搜索了很多答案后的理解是,当您在 IB 中对按钮进行子类化时,initWithFrame 永远不会被调用。相反,我应该使用 initWithCoder。这是正确的吗 ?如果是这样,那么我不知道 NSCoder 是什么,以及如何使用它。
我厌倦了为此寻找解决方案,请帮助我。
【问题讨论】:
-
你在IB做点什么吗?您正在代码中创建此按钮,因此应该调用 initWithFrame: -- 只需在其中输入一个日志进行测试。我认为更大的问题是 buttonPressed: 方法应该在您的视图控制器中而不是在按钮代码中——这是标准的 MVC 设计。
-
@Farhan 你能解决这个问题吗?关于我的答案,我可以解释更多吗?
标签: ios uibutton gui-builder