如何在退出视图之前提示警报

时间:2015-02-21 09:37:18

标签: ios swift

我试图创建一个弹出提示,但我做错了。我有一个按钮,我应该在按下时更改View Controllers,有点像导航栏上的后退按钮但没有导航栏。我希望警报弹出以确认"是或否"在实际离开视图之前。目前我的代码只是转换回View Controller,我将其链接到没有提示的情况下。有什么想法吗?

@IBAction func exit(sender: AnyObject) {


var alert = UIAlertController(title: "Wait", message: "Are you sure you want to exit?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)


}

1 个答案:

答案 0 :(得分:0)

首先自定义viewdidload方法

override func viewDidLoad() {
    super.viewDidLoad()
    var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    myBackButton.addTarget(self, action: "goback:", forControlEvents: UIControlEvents.TouchUpInside)
    myBackButton.setTitle("YOUR TITLE", forState: UIControlState.Normal)
    myBackButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
    myBackButton.sizeToFit()
    var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
    self.navigationItem.leftBarButtonItem  = myCustomBackButtonItem
}

然后implement自定义back button action

func goback(sender:UIBarButtonItem){
       var refreshAlert = UIAlertController(title: “Wait”, message: "Are you sure you want to exit?
", preferredStyle: UIAlertControllerStyle.Alert)

    refreshAlert.addAction(UIAlertAction(title: “YES”, style: .Default, handler: { (action: UIAlertAction!) in
      println("Handle YES logic here")
      self.navigationController?.popViewControllerAnimated(true)

      }))

    refreshAlert.addAction(UIAlertAction(title: “NO”, style: .Default, handler: { (action: UIAlertAction!) in
      println("Handle NO Logic here")
      }))

}