代码之家  ›  专栏  ›  技术社区  ›  Hassy

iOS-UIButton作为UIAlertController上的子视图,不触发事件

  •  0
  • Hassy  · 技术社区  · 8 年前

    我正在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];
    

    按钮似乎高亮显示,但相应的事件未触发。

    这里有什么问题?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Puneet Sharma    8 年前

    这是来自 UIAlertController documentation .

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

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

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