簡體   English   中英

Swift:在UIAlertController中訪問文本字段/ segue到新的ViewController

[英]Swift: Accessing the textfield/segue to a new ViewController in UIAlertController

我正在使用UIAlertController來顯示textField以輸入電話號碼。 單擊“確定”時,我希望將文本字段的文本內容存儲在變量中,以便對其進行一些操作。 這是代碼:

@IBAction func popup(sender : AnyObject) {
    var popupText: String = ""
    func config(textField: UITextField!)->Void{
        popupText = textField.text
    }

    var alc: UIAlertController = UIAlertController(title: "Phone", message: "Please enter phone #: ", preferredStyle: UIAlertControllerStyle.Alert)
    alc.addTextFieldWithConfigurationHandler(config)
    alc.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default, handler:{ UIAlertAction in
            print(popupText)
            self.performSegueWithIdentifier("popupSegue", sender: alc)


        }))
    alc.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
    self.presentViewController(alc, animated: true, completion: nil)
}

當我嘗試訪問popupText並打印其內容時,它似乎為空,因為控制台未顯示任何內容。 有沒有辦法訪問此textField的內容,甚至沒有它的標識符? (UIAlertController似乎沒有讓我嘗試“ alc.textField.text”),我猜我對“ config”的處理方式是錯誤的,但是我仍然不知道如何訪問此控制器的文本字段。任何幫助將不勝感激,謝謝!

您進行此操作的方式存在一些問題。

設置文本字段

    var popupText: String = ""
    func config(textField: UITextField!)->Void{
        popupText = textField.text
    }
    ...
    alc.addTextFieldWithConfigurationHandler(config)

您傳遞給addTextFieldWithConfigurationHandlerconfig處理程序用於配置新的文本字段,但看起來您正在嘗試訪問其值。 文本字段是全新的,因此將為空,我認為這對您沒有太大幫助。 如果您需要更改文本字段的某些屬性,則此位置正確,否則只需將nil傳遞給addTextField...

    func config(textField: UITextField!)->Void{
        textField.textColor = UIColor.redColor()
    }

訪問文本字段的值

    alc.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default, handler:{ UIAlertAction in
        print(popupText)
        self.performSegueWithIdentifier("popupSegue", sender: alc)
    }))

這里有兩個問題popupText只是一個空的String變量,它沒有以任何方式鏈接到文本字段,警報操作或警報控制器。 您想訪問文本字段本身,可以使用alc.textFields[0]進行查找。 其次,看起來您希望將text字段的值存儲在popupText ,但這是此方法的局部變量,在其他任何地方都無法訪問。 根據您要使用的功能,我可能建議將電話號碼存儲在您的類的instance屬性中。 無論如何,您都想要這樣的東西:

    alc.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default, handler:{ UIAlertAction in
        println(alc.textFields[0].text)
        self.performSegueWithIdentifier("popupSegue", sender: alc)
    }))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM