我有两个以编程方式创建和设置目标的UIButton。如果我将这些按钮添加到主视图中,那么一切都会很好地工作。但是,当我先将子视图添加到子视图并将该子视图添加到主视图时,触摸事件不起作用。我猜这些按钮被遮盖了。

如何在将这些按钮保留在子视图中的同时发现这些按钮?

这是我的代码:

// Create button panel here
UIImage *buttonPanel = [UIImage imageNamed:@"left_button_background"];
UIImageView *buttonPanelView = [[UIImageView alloc] initWithImage:buttonPanel];
[buttonPanelView setFrame:CGRectMake(20, 186, 363, 345)];

// Populate the panel with buttons
UIButton *cmsButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 351, 142)];
[cmsButton setImage:[UIImage imageNamed:@"BTN_MATLIB"] forState:UIControlStateNormal];
[cmsButton addTarget:self action:@selector(loadCMS) forControlEvents:UIControlEventTouchDown];
[buttonPanelView addSubview:cmsButton];
[self setCms:cmsButton];

UIButton *calcButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 196, 351, 142)];
[calcButton setImage:[UIImage imageNamed:@"BTN_MORE_RESOURCES"] forState:UIControlStateNormal];
[calcButton addTarget:self action:@selector(loadCalc) forControlEvents:UIControlEventTouchDown];
[buttonPanelView addSubview:calcButton];
[self setCalc:calc];

[[self view] addSubview:buttonPanelView];

最佳答案

图像视图默认情况下未启用用户交互,这意味着它们的子视图均无法接收用户交互。

buttonPanelView.userInteractionEnabled = YES;

关于ios - addTarget不适用于iOS中的UIButton, View 已遮盖,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8738158/

10-12 06:06