How to create an alert box in iphone?

后端 未结 10 2126
我寻月下人不归
我寻月下人不归 2020-12-23 21:30

I would like to make an alert type box so that when the user tries to delete something, it says, \"are you sure\" and then has a yes or no for if they are sure. What would b

10条回答
  •  有刺的猬
    2020-12-23 22:01

    The post is quite old, but still a good question. With iOS 8 the answer has changed. Today you'd rather use 'UIAlertController' with a 'preferredStyle' of 'UIAlertControllerStyle.ActionSheet'.

    A code like this (swift) that is bound to a button:

    @IBAction func resetClicked(sender: AnyObject) {
        let alert = UIAlertController(
            title: "Reset GameCenter Achievements",
            message: "Highscores and the Leaderboard are not affected.\nCannot be undone",
            preferredStyle: UIAlertControllerStyle.ActionSheet)
        alert.addAction(
            UIAlertAction(
                title: "Reset Achievements",
                style: UIAlertActionStyle.Destructive,
                handler: {
                    (action: UIAlertAction!) -> Void in
                    gameCenter.resetAchievements()
                }
            )
        )
        alert.addAction(
            UIAlertAction(
                title: "Show GameCenter",
                style: UIAlertActionStyle.Default,
                handler: {
                    (action: UIAlertAction!) -> Void in
                    self.gameCenterButtonClicked()
                }
            )
        )
        alert.addAction(
            UIAlertAction(
                title: "Cancel",
                style: UIAlertActionStyle.Cancel,
                handler: nil
            )
        )
        if let popoverController = alert.popoverPresentationController {
            popoverController.sourceView = sender as UIView
            popoverController.sourceRect = sender.bounds
        }
        self.presentViewController(alert, animated: true, completion: nil)
    }
    

    would produce this output: enter image description here

    EDIT: The code crashed on iPad, iOS 8+. If added the necessary lines as described here: on another stack overflow answer

提交回复
热议问题