在 UIAlertController 中添加复选框

add checkbox in UIAlertController

我需要在警报中添加一个复选框,询问我是否应该再次显示此消息。我遇到过各种示例,其中在控制器中添加了按钮或文本字段,但在任何地方都没有看到复选框。 UIAlertView 在版本 9 以上已弃用,所以我不想使用它。

UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:@"Should I remind?" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  [self goToAddReminderView];
}];
UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
[self.navigationController popViewControllerAnimated:YES];
}];

[alert addAction:yesAction];
[alert addAction:noAction];

[self presentViewController:alert animated:YES completion:nil];

我会举个例子。

iOS 本身不支持。您需要创建自己的自定义控件。

你可以试试https://www.cocoacontrols.com/controls/fcalertview and https://www.cocoacontrols.com/controls/cfalertviewcontroller

您必须像下面那样自定义 UI。

我刚刚编写了简单的工作代码片段并且运行良好。

func showAlertController()
    {
        //simple alert dialog
        let alertController = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.alert);
        // Add Action
        alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil));
        //show it
        let btnImage    = UIImage(named: "checkBoxImage")!
        let imageButton : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        imageButton.setBackgroundImage(btnImage, for: UIControlState())
        imageButton.addTarget(self, action: #selector(ViewController.checkBoxAction(_:)), for: .touchUpInside)
        alertController.view.addSubview(imageButton)
        self.present(alertController, animated: false, completion: { () -> Void in

            })
    }


func checkBoxAction(_ sender: UIButton)
{
    if sender.isSelected
    {
        sender.isSelected = false
        let btnImage    = UIImage(named: "checkBoxImage")!
        sender.setBackgroundImage(btnImage, for: UIControlState())
    }else {
        sender.isSelected = true
        let btnImage    = UIImage(named: "unCheckBoxImage")!
        sender.setBackgroundImage(btnImage, for: UIControlState())
    }
}