ios - 以编程方式在 iOS 上创建了一个按钮,但按下时没有任何 Action

标签 ios uibutton

我创建了一个按钮,就像下面的代码一样,但它不会在日志中响应(应该显示“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/

相关文章:

ios - Swift 如何以编程方式移动 UIButton?

ios - 增加 UIButton 中图像的大小

ios - 多目标 Xcode 7.3 iOS 9+ 应用程序启动屏幕 xib 问题

html - 我的网站在 iOS 上不显示图像

ios - 无法反汇编 iOS 银行应用程序

ios - 如何画一个平行四边形按钮

objective-c - UIButton 中的图像比原始图像更暗

ios - 自定义 UIScrollView 滚动条颜色?

ios - UserInteractionEnabled 是否像 UIView 层次结构的 Alpha 一样工作?

带有右导航箭头的 iOS 联系人样式按钮