【发布时间】:2011-06-22 16:57:26
【问题描述】:
我正在创建 UIButton 的子类,以便创建自己的自定义按钮。我的代码如下:
//interface file (subclass of uIButton
@interface UICustomButton : UIButton
{
Answer *answer;
NSString *btnType;
}
@property (nonatomic, retain) Answer *answer;
@property (nonatomic, assign) NSString *btnType;
- (id)initWithAnswer:(Answer *)ans andButtonType:(NSString *)type andFrame:(CGRect)frame;
- (void)buttonPressed;
@end
//Implementation file (.m)
@implementation UICustomButton
@synthesize answer,btnType;
- (id)initWithAnswer:(Answer *)ans andButtonType:(NSString *)type andFrame:(CGRect)frame;
{
self = [super initWithFrame:frame];
if (self)
{
self = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
self.backgroundColor = [UIColor colorWithHexString:@"#E2E4E7"];
}
[self addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlStateNormal];
self.answer = ans;
self.btnType = type;
return self;
}
我在使上述代码正常工作时遇到了一些问题。我有两个问题
1) 按钮没有响应选择器方法“buttonPressed”
2) 我在 'self.answer = ans' 和 'self.btnType = type' 行中遇到运行时错误堆栈跟踪如下:
-[UIButton setAnswer:]: unrecognized selector sent to instance 0x614ebc0
2011-06-23 00:55:27.038 onethingaday[97355:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton setAnswer:]: unrecognized selector sent to instance 0x614ebc0'
我在这里做错了什么?
【问题讨论】:
-
我发现只在子类中调用[super init]是行不通的,至少在iOS8中是这样。它只是简单地返回零。所以我调用[super initWithFrame:CGRectZero],然后你必须在代码中设置一些大小...
-
@albertamg,您应该考虑删除您的评论!现在是 2015 年,是错误的和过时的。
-
@IulianOnofrei 你是对的。该评论已有 4 年历史,现在已过时。
标签: objective-c ios uibutton