我正在尝试编写一个方便方法,该方法返回UIButton
并将标题,CGRect和操作作为参数。我的代码编译并运行,但是当我实际点击按钮时崩溃。
这是我的便捷方法:
+ (UIButton *)makeButton:(NSString *)title withRect:(CGRect)rect
withAction:(SEL)selectorX {
// setup button properties
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = rect;
[btn setFont:[UIFont boldSystemFontOfSize:20]];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[btn setBackgroundImage:[[UIImage imageNamed:@"btn_21.png"]
stretchableImageWithLeftCapWidth:10.0
topCapHeight:0.0] forState:UIControlStateNormal];
[btn setTitle:@"TEST" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(selectorX:)
forControlEvents:UIControlEventTouchUpInside];
return btn;
}
以下是我如何称呼它:
- (void)viewDidLoad {
[super viewDidLoad];
btn = [Utilities makeButton:@"TEST" withRect:CGRectMake(10, 100, 236, 45)
withAction:@selector(buttonActionTEST:)];
[self.view addSubview:btn];
}
- (void) buttonActionTEST:(id)sender {
[Utilities alert:@"yo yo yeoman"];
}
答案 0 :(得分:1)
您需要同时提供目标和选择器来调用该目标。您只提供选择器,然后执行此操作:
[btn addTarget:self action:@selector(selectorX:)
forControlEvents:UIControlEventTouchUpInside];
两个帐户上的错误:首先,此上下文中的 self 评估为类Utilities
(甚至不是实例,而是Class对象)。然后,当您传递硬编码选择器selectorX:
而不是具有几乎相同名称的变量时,您尝试提供选择器也是错误的。它应该这样做:
+ (UIButton *)makeButton:(NSString *)title withRect:(CGRect)rect
target:(id)aTarget action:(SEL)anAction {
...
[btn addTarget:aTarget action:anAction
forControlEvents:UIControlEventTouchUpInside];
...
}
然后你这样称呼它:
btn = [Utilities makeButton:@"TEST" withRect:CGRectMake(10, 100, 236, 45)
target:self action:@selector(buttonActionTEST:)];
答案 1 :(得分:0)
您的便捷方法已经将选择器作为参数 - 它确实是一个选择器,因此靠近该方法的底部使用:
[btn addTarget:self action:selectorX forControlEvents:UIControlEventTouchUpInside];
(无需在@selector()中包含selectorX,因为 是一个选择器。)
答案 2 :(得分:0)
我认为问题来自这条线:
[btn addTarget:self action:@selector(selectorX:) forControlEvents:UIControlEventTouchUpInside];
不会“自我”有公用事业课吗?另外我认为你不需要@selector。