Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add checkbox in UIAlertController

I need to add a check box in the alert asking if I should show this message again. I came across various examples where a button or a text field was added in the controller but didn't see a checkbox anywhere. UIAlertView is deprecated above version 9 so I don't want to use that.

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];

I would appraciate an example.

like image 249
Astha Gupta Avatar asked Dec 29 '16 06:12

Astha Gupta


2 Answers

There is not support by iOS natively. You need to create your own custome control.

You can try with https://www.cocoacontrols.com/controls/fcalertview and https://www.cocoacontrols.com/controls/cfalertviewcontroller

like image 148
SandeepM Avatar answered Oct 20 '22 07:10

SandeepM


You have to customize UI like bellow.

I have just written simple working code snippet and it is working fine.

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())
    }
}
like image 38
Nilesh Avatar answered Oct 20 '22 07:10

Nilesh