停止Segue并传递给下一个查看alert-Swift中显示的文本字段的内容

时间:2015-03-06 14:18:03

标签: ios iphone swift segue

我需要停止segue转换并使用textField显示警告。 但是,当我按“确定”按钮时,我想传递给下一个视图,即textfield的内容。

问题是当我在prepareForSegue中声明一个视图控制器目标并传递文本时,因为这是零。我写下我的例子:

override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
    var shouldSegue:Bool = true
    if identifier == "FirstToSecondView" {

        var alert = UIAlertController(title: "End the First", message: "Are you sure you want to end the first?", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addTextFieldWithConfigurationHandler{ (textField) in
               textField.placeHolder = "Name"
        }
        presentViewController(alert, animated: true, completion: nil)

        var okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
            UIAlertAction in
            println("OK Pressed")
            let tf = alert.textFields?.First as? UITextField

            //name is a declared variable above
            if tf != nil {self.name = tf.text}

            self.performSegueWithIdentifier("WorkoutToSummary", sender: self)
        }
        var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
            UIAlertAction in
            println("Cancel Pressed")
            shouldSegue = false
        }
        alert.addAction(okAction)
        alert.addAction(cancelAction)
    }
    return shouldSegue
}

然后在prepareForSegue,我说:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
    var namePass: String = self.name
    if segue.identifier == "FirstToSecondView" {
        let secondViewController = segue.destinationViewController as SecondViewController
        secondViewController.name = namePass
    }
}

但是在prepareForSegue启动时,self.name为nil

提前致谢!!

1 个答案:

答案 0 :(得分:0)

首先,您要做的是为警报设置标签

alert.tag = 1

在视图控制器中创建一个变量

class SBViewController : UIViewController{
//GlobalVariables
var demoText : String = String()

override func viewDidLoad(){
super.viewDidLoad()
}
}

为您的警报视图编写委托方法,并将警报视图委托设置为自己

alert.delegate = self
var name : String = String()



  func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {

            if alertView.tag == 20 {
                if alertView.buttonTitleAtIndex(buttonIndex) == "OK"{
                    var textFeild : UITextField = alertView.textFieldAtIndex(0)!
                    if textFeild.text != "" {
                    name =  textFeild.text


                  }

                }
            }