我正在以编程方式创建按钮,然后我想添加功能,当它们被点击/按下时,它们会保持突出显示,除非再次点击。我现在正在做的是创建按钮,然后尝试添加一个 IBAction。但是,问题是我在一个方法中创建了按钮,然后我不确定如何在我的 IBAction 中引用该按钮。这是我的代码:
UIButton* testButn = [UIButton buttonWithType:UIButtonTypeCustom];
[testButn setFrame:CGRectMake(0, 135, 40, 38)];
[testButn setImage:[UIImage imageNamed:@"test_butn_un.png"] forState:UIControlStateNormal];
[testButn setImage:[UIImage imageNamed:@"test_butn_pressed.png"] forState:UIControlStateHighlighted];
[testButn addTarget:self action:@selector(staypressed:) forControlEvents:UIControlEventTouchUpInside];
[self.contentview addSubview:testButn
-(IBAction)staypressed:(id)sender{
//Not sure what to do here, since this method doesn't recognize testButn, How do I reference testButn
最佳答案
发件人是testButn。您应该将 stayPressed 的参数类型从 (id) 更改为 (UIButton *)
除非一个 Action 方法连接到几个不同的对象类,否则最好将 id 替换为您正在使用的任何对象类。如果您在 IB 中 Hook ,这会很有用,因为它不会让您 Hook 到错误类型的对象。
它无法正常工作并不是因为它无法识别您的按钮。你的做法是错误的。我认为您需要连接一个 Action 才能着陆,并且可能将选定状态设置为"is"。在您的按钮定义中,您需要为选定状态设置一个 imageForState:。按照您现在的操作方式,该方法直到润色后才会被调用。
像这样:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton* testButn = [UIButton buttonWithType:UIButtonTypeCustom];
[testButn setFrame:CGRectMake(0, 135, 40, 38)];
[testButn setImage:[UIImage imageNamed:@"New_PICT0019.jpg"] forState:UIControlStateNormal];
[testButn setImage:[UIImage imageNamed:@"New_PICT0002.jpg"] forState:UIControlStateSelected];
[testButn addTarget:self action:@selector(stayPressed:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:testButn];
}
-(void)stayPressed:(UIButton *) sender {
if (sender.selected == YES) {
sender.selected = NO;
}else{
sender.selected = YES;
}
}
关于ios - IBAction 和按钮以编程方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14630349/