我正在以编程方式创建按钮,然后我想添加功能,当按下/按下它们时,除非再次点击,否则它们会保持高亮显示。我现在正在做的是创建按钮,然后尝试添加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
答案 0 :(得分:9)
发件人是testButn。您应该将stayPressed的参数类型从(id)更改为(UIButton *)
除非动作方法连接到几个不同类的对象,否则最好用您正在使用的任何对象类替换id。如果你在IB中挂钩,这可能很有用,因为它不会让你把它挂钩到错误的对象上。
它无效的事实不是因为它无法识别您的按钮。你的方法是错的。我认为您需要将一个动作连接到触地,并可能将所选状态设置为YES。在按钮定义中,您需要为所选状态设置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;
}
}
答案 1 :(得分:2)
您需要将发件人转发给UIButton。
- (IBAction)staypressed:(id)sender
{
UIButton *theButton = (UIButton*)sender;
//do something to theButton
}
答案 2 :(得分:2)
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];
testButn.tag = 1;
[self.contentview addSubview:testButn
-(IBAction)staypressed:(id)sender
{
if ([sender tag]==1)
{
somecodes...
}
}