4

我创建了一个按钮,就像下面的代码一样,但它不会在日志中响应(应该显示“ha”)。最奇怪的部分是我已经能够让这个确切的代码在集合视图中工作,但通常不能在视图控制器上工作。按下“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");
}
4

2 回答 2

6

1)

您不需要resignFirstResponder在按钮上使用“”(似乎大多数时候我看到“ resignFirstResponder”是在文本字段或文本视图中)。

2)

将控件事件从 UIControlEventTouchUpInside 更改为 UIControlEventTouchDown

3)

父 UIImageView 可能没有“ userInteractionEnabled”设置为 true,这意味着事件不会被传播(或发送)到子视图。

要使这些事件可用于子视图,请通过以下方式更改父视图的 userInteractionEnabled 属性:

backImageView.userInteractionEnabled = YES;

在添加该子视图之前。

于 2013-07-23T22:07:43.487 回答
1

默认情况下,图像userInteractionEnabled是禁用的。所以,你必须通过backImageView.userInteractionEnabled = YES;

于 2016-04-16T12:22:21.500 回答