UIAlertView没有返回适当的值

时间:2016-02-19 05:59:06

标签: ios swift uiviewcontroller uialertview uialertcontroller

这是我的代码

import Foundation
import UIKit

class Alert: UIViewController {


class func showAlert(title: String, message: String, buttonTitle: String? = nil, buttonTitle2: String? = nil, sender: UIViewController) -> Int? {
    var flag : Int?
    func yes(){
        flag = 1

    }
    func no(){
        flag = 0

    }
     //= nil  ;
    if objc_getClass("UIAlertController") != nil {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        if (buttonTitle != nil){
            alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in
            yes()


        }))
        }
        if (buttonTitle2 != nil)  {
            alert.addAction(UIAlertAction(title: buttonTitle2, style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in
                no()

            }))
        }


        sender.presentViewController(alert, animated: true, completion: nil)

       return flag


    } else {
        let alert = UIAlertView()
        alert.title = title
        alert.message = message
        alert.addButtonWithTitle(buttonTitle)
        alert.addButtonWithTitle(buttonTitle2)
        print("inside Else")

        alert.show()
        return flag
        //make and use a UIAlertView
    }

}


}

问题是返回的标志对于我调用Alert from的视图控制器总是为零。如果"是"我需要标志返回1按下,如果"否"被压了。我很多时候都遇到过这个问题。帮助

2 个答案:

答案 0 :(得分:2)

试试这段代码,

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func showAlert() {
    let alertController = UIAlertController(title: "Hey there", message: "Do you want to do it?", preferredStyle: .Alert)

    let btnAction1 = UIAlertAction(title: "Yes", style: .Default) { (action : UIAlertAction) -> Void in
        self.yes()
    }

    let btnAction2 = UIAlertAction(title: "No", style: .Default) { (action : UIAlertAction) -> Void in
        self.no()
    }

    alertController.addAction(btnAction1)
    alertController.addAction(btnAction2)

    presentViewController(alertController, animated: true, completion: nil)
}

func yes() -> Int
{
    print("Yes")
    return 1
}

func no() -> Int
{
    print("No")
    return 0
}
}

它的工作正常,我希望它也能为你工作.. :)

答案 1 :(得分:0)

你犯了一个错误,在按钮被点击之前不会执行闭包但是函数现在会返回。你应该为这个函数提供一个闭包。它看起来像:

class func showAlert(title: String, message: String, buttonTitle: String? = nil, buttonTitle2: String? = nil, sender: UIViewController,handler: ((Bool) -> Void)) -> Void

并按照以下方式处理警报:

handler(true)
相关问题