Search code examples
iosswiftuialertcontroller

UIAlertController: How to make the right button bolded?


When I run the following code, the Yes button is always on the left side, how can I change it to right side and keep it bolded?

func showInAppPurchaseAlert() {
    let alertController = UIAlertController.init(title: "Upgrade?", message: "Do you want to upgrade to pro version?", preferredStyle: .alert)
    alertController.addAction(UIAlertAction.init(title: "No", style: .default, handler: { action in
        self.dismiss(animated: true, completion: nil)
    }))
    let actionUpgrade = UIAlertAction.init(title: "Yes", style: .cancel, handler: { action in
        self.upgradeToPro()
    })
    alertController.addAction(actionUpgrade)
    alertController.preferredAction = actionUpgrade
    self.present(alertController, animated: true, completion: nil)
}

Solution

  • The .default style will always have the right side, and the .cancel style the bold text. In order for you to change that, you have to set the preferredAction like you did in your code, but the problem was that you were using .cancel on your "Yes" action, which you wanted on the right side and your "No" action to .default. I tried your code, and this version works for me with your requirements.

    func showInAppPurchaseAlert() {
        let alertController = UIAlertController.init(title: "Upgrade?", message: "Do you want to upgrade to pro version?", preferredStyle: .alert)
        alertController.addAction(UIAlertAction.init(title: "No", style: .cancel, handler: { action in
            self.dismiss(animated: true, completion: nil)
        }))
        
        let actionUpgrade = UIAlertAction.init(title: "Yes", style: .default, handler: { action in
            self.upgradeToPro()
        })
        alertController.addAction(actionUpgrade)
    
        alertController.preferredAction = actionUpgrade
    
        self.present(alertController, animated: true, completion: nil)
    }