【问题标题】:iOS - UIButton as Subview on UIAlertController not firing eventsiOS - UIButton 作为 UIAlertController 上的子视图不触发事件
【发布时间】:2025-12-30 06:40:09
【问题描述】:

我在 UIAlertController 上添加 UIButton,但它没有触发任何事件的方法。

UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[cancelBtn setFrame:CGRectMake((_alertController.view.frame.size.width/2)-30, _alertController.view.frame.size.height-50, 60, 30)];
[cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];
[cancelBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[cancelBtn setBackgroundColor:[UIColor orangeColor]];
[cancelBtn addTarget:self action:@selector(forceFullDismiss_FireDelegate:) forControlEvents:UIControlEventTouchUpInside];
cancelBtn.showsTouchWhenHighlighted = YES;

[_alertController.view setUserInteractionEnabled:YES];
[_alertController.view addSubview:cancelBtn];

按钮似乎突出显示,但相应的事件没有触发。

这里有什么问题?

【问题讨论】:

  • 并且没有关于目标的错误?断点不会停在forceFullDismiss_FireDelegate ?
  • 无错误。是的,断点不会停在 forceFullDismiss_FireDelegate

标签: ios objective-c uibutton uialertcontroller


【解决方案1】:

这是来自UIAlertControllerdocumentation

UIAlertController 类旨在按原样使用,而不是 支持子类化。此类的视图层次结构是私有的,并且 不得修改。

如果要添加取消按钮,可以使用

UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    //  action on cancel
}];

[_alertController addAction:cancel];

【讨论】: