Dav*_*est 4 objective-c uibutton ibaction ios uistoryboard
我正在以编程方式创建按钮,然后我想添加功能,当他们点击/按下它们时,除非再次点击,否则它们会保持高亮显示.我现在正在做的是创建按钮,然后尝试添加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
Run Code Online (Sandbox Code Playgroud)
发件人是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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11513 次 |
最近记录: |