我已经为UIButton创建了一个子类,并希望将自定义属性传递给它。但是,它没有用,我从那以后就读到了UIButton的子类化并不是一个好主意。
我的问题是如何为按钮分配自定义属性?我正在创建一个按钮,该按钮被放置在分组表的标题视图中。我想传递给那个按钮的节号。我已经在每一行中成功完成了UISwitch,但不能对UIButton使用相同的方法。
所以我创建了一个按钮
MattsButtonClass *button = [MattsButtonClass buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(240, 15, 45, 30);
button.MFsectionNo = section; //this would be 1, 2 etc
//etc
那么我该怎么做呢?你会看到我的UI按钮有一个子类,看起来像这个
//.h file
@interface MattsButtonClass : UIButton {
int MFsectionNo;
}
@property (nonatomic) int MFsectionNo;
@end
//.m file
@implementation MattsButtonClass
@synthesize MFsectionNo;
@end
以上错误是
-[UIRoundedRectButton MFsectionNo:]: unrecognized selector sent to instance 0x5673650
2010-09-07 22:41:39.751 demo4[67445:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UIRoundedRectButton MFsectionNo:]: unrecognized selector sent to instance 0x5673650'
我想要的不可能吗?谢谢你的帮助...
答案 0 :(得分:5)
您可以使用tag
的{{1}}属性来存储您的节号(可能带有偏移,因为UIButton
默认为0)
答案 1 :(得分:2)
这是不可能的,因为您正在使用函数调用:
[MattsButtonClass buttonWithType:UIButtonTypeCustom]
该消息将返回UIButton 而不是 MattsButtonClass。这就是返回对象上不存在该属性的原因。这使得UIButton的子类化变得困难。但是,您可以通过以下方式实现所需的功能:
MattsButtonClass *button = [[MattsButtonClass alloc] initWithFrame:CGRectMake(240, 15, 45, 30)];
button.MFsectionNo = section;
答案 2 :(得分:0)
也许保留一个引用每个节头中按钮的数组?
-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIButton *myButton = [[UIButton alloc] init]; [myButton addTarget:self action:@selector(myButton_touchUpInside:) forControlEvents:UIControlEventTouchUpInside]; // previously defined as an instance variable of your viewcontroller // NSMutableArray *sectionHeaderButtons; [sectionHeaderButtons insertObject:myButton atIndex:section]; }
然后在按钮的TouchUpInside事件的处理程序中:
- (void)myButton_touchUpInside:(id)sender { int i; for (i = 0; i < [sectionHeaderButtons count]; i++) { if ([sectionHeaderButtons objectAtIndex:i] == sender) break; // now you know what section index was touched } }
如果触摸按钮的部分索引是您所追求的,那么这应该可以解决问题。但是,如果符合以下条件,则不是最佳选择:
希望这有帮助。