iOS按钮操作无效

时间:2015-04-20 21:26:55

标签: ios objective-c

我对iOS UIButton有一个奇怪的问题。

我有一个UIViewController课程:

@interface CustomViewController : UIViewController

在这个类的内部,我有一个名为customLabel的标签。在这个标签中我有一个按钮子视图:

UIButton *addButton = [[UIButton alloc] init];

[customButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
[customButton addTarget:self action:@selector(customButtonClicked) forControlEvents:UIControlEventTouchUpInside];

[customLabel insertSubview:customButton atIndex:1];

当然,行动方法:

- (void)customButtonClicked
{
    NSLog(@"- (void)customButtonClicked");
}

我还有一个这个视图控制器的子类:

@interface MyNewCustomViewController : CustomViewController

此视图控制器在UIWindow中加载:

[self.navigationController pushViewController: myNewCustomViewController animated:YES];

一切似乎都很好,带按钮的标签位于正确的位置,除了按钮点击没有调用动作方法......

也许你知道,问题出在哪里?

1 个答案:

答案 0 :(得分:1)

只要您在当前按钮的顶部没有其他视图,就会在视图上启用用户互动。这应该工作。

// First make sure userInteractionEnabled is enabled for your custom label which will contain your button as a subview 
customLabel.userInteractionEnabled = YES;

// Then create and add your button as a subview
UIButton *addButton = [[UIButton alloc] init];
[customButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
[customButton addTarget:self action:@selector(customButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[customLabel addSubview:addButton]; // Places view on top index