Quick implementation:
class Controller: UIViewController { var isFirstButtonChecked = true @IBAction func buttonTapped(_ sender: UIButton?) { let firstButton = UIAlertAction(title: "First Button", style: .default, handler: { [unowned self] _ in self.isFirstButtonChecked = true print("First Button tapped") }) //Here the main magic; it called Key-Value Coding, or KVC: firstButton.setValue(isFirstButtonChecked, forKey: "checked") let secondButton = UIAlertAction(title: "Second Button", style: .default, handler: { [unowned self] _ in self.isFirstButtonChecked = false print("Second Button tapped") }) secondButton.setValue(!isFirstButtonChecked, forKey: "checked") let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.addAction(firstButton) alert.addAction(secondButton) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } }
You can also check the box for more buttons using the enumeration :
class Controller: UIViewController { enum ButtonChecked { case first case second case third case forth } var buttonChecked: ButtonChecked = .first @IBAction func buttonTapped(_ sender: UIButton?) { let firstButton = UIAlertAction(title: "First Button", style: .default, handler: { [unowned self] _ in self.buttonChecked = .first print("First Button tapped") }) let secondButton = UIAlertAction(title: "Second Button", style: .default, handler: { [unowned self] _ in self.buttonChecked = .second print("Second Button tapped") }) let thirdButton = UIAlertAction(title: "Third Button", style: .default, handler: { [unowned self] _ in self.buttonChecked = .third print("Third Button tapped") }) let forthButton = UIAlertAction(title: "Forth Button", style: .default, handler: { [unowned self] _ in self.buttonChecked = .forth print("Forth Button tapped") }) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) switch buttonChecked { case .first: firstButton.setValue(true, forKey: "checked") case .second: secondButton.setValue(true, forKey: "checked") case .third: thirdButton.setValue(true, forKey: "checked") case .forth: forthButton.setValue(true, forKey: "checked") } let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.addAction(firstButton) alert.addAction(secondButton) alert.addAction(thirdButton) alert.addAction(forthButton) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } }
source share