I am creating a subclass of UIButton in order to create my own customized buttons. My code as follows:
//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;
}
I am facing some issues in getting the above code to work. I have 2 problems
1) The buttons are not responding to the selector method “buttonPressed”
2) I am hitting a runtime error for the lines ‘self.answer = ans’ and ‘self.btnType = type’ Stack trace as follows:
-[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'
What am I doing wrong here?
This is happening because you are creating a
UIButtontype object and not aUICustomButtontype inside the init method when you doTry replacing your
initmethod forThis will cause
selfto be aUICustomButtontype object.Also, you are using a wrong type for the UIControlState parameter when you add the target to your button using the
addTarget:action:forControlEvents:methodYou should use value among the ones bellow:
EDIT:
Notes on UIButton subclassing
Many references on the web say you should NOT subclass the
UIButtonclass, but not only anybody said why but what also deeply annoyed me was that the UIButton Class Reference does not say anything about it at all.If you take UIWebView Class Reference for example, it explicitly states that you should not subclass
UIWebViewthe big deal with
UIButtonis that it inherits fromUIControland a good and simple explanation is on the UIControl Class Reference itselfSo, this means that you CAN subclass a
UIButton, but you should be careful on what you are doing. Just subclass it to change its behavior and not its appearance. To modify aUIButtonappearance you should use the interface methods provided for that, such as:References worth reading
Source: my post here