我创建了一个按钮,就像下面的代码一样,但它不会在日志中响应(应该显示“ha”)。最奇怪的部分是我已经能够让这个确切的代码在 Collection View 中工作,但通常不能在 View Controller 上工作。按“myAction”按钮我做错了什么?
-(void)viewDidLoad {
UIButton *buttonz = [UIButton buttonWithType:UIButtonTypeCustom];
buttonz.frame = CGRectMake(160, 0, 160, 30);
[buttonz setTitle:@"Charge" forState:UIControlStateNormal];
[buttonz addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[buttonz setEnabled:YES];
[buttonz setBackgroundColor:[UIColor blueColor]];
//add the button to the view
[backImageView addSubview:buttonz];
}
-(void)myAction:(id)sender {
NSLog(@"ha");
[self resignFirstResponder];
NSLog(@"ha");
}
最佳答案
1)
您不需要在按钮上使用“resignFirstResponder
”(似乎大多数时候我看到“resignFirstResponder
”是在文本字段或 TextView 中)。
2)
将控件事件从 UIControlEventTouchUpInside 更改为 UIControlEventTouchDown
3)
父 UIImageView 可能没有将“userInteractionEnabled
”设置为 true,这意味着事件不会传播(或发送)到 subview 。
要使这些事件对 subview 可用,请通过以下方式更改父 View 的 userInteractionEnabled 属性:
backImageView.userInteractionEnabled = YES;
在添加该 subview 之前。
关于ios - 以编程方式在 iOS 上创建了一个按钮,但按下时没有任何 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17821816/