警报不会在预期的时候弹出

时间:2018-09-16 11:01:15

标签: ios swift uialertcontroller

我想更改标签的文本。

@IBAction func renameLabel(_ sender: UIButton) {
        let labelTextToBeChanged = "some text"
        let changedLabelText = changeLabeltext(text: labelTextToBeChanged!)
        // Do something
        print("changedLabelText: \(changedLabelText)")
}

函数changeLabeltext()包含一个警报控制器,如下所示。 我希望在调用changeLabeltext(text:labelTextToBeChanged!)之后会弹出一个警报窗口,并且在修改文本之后,将新的文本ist分配给changedLabelText并打印出来。 但是,在该函数调用后,将打印出一个空文本,然后退出IBAction函数,然后弹出警报窗口。我在做什么错了?

func changeLabeltext(text: String) -> String{
    var inputTextField:UITextField?

    // Create the controller
    let alertController = UIAlertController(
        title: "Ändere Projekt- oder Versionsname",
        message: "",
        preferredStyle: .alert)

    // Create a textfield for input
    alertController.addTextField{
        (textField: UITextField!) -> Void in
        textField.placeholder = text
        inputTextField = textField
    }

    // Create the actions
    let saveAction = UIAlertAction(
        title: "Speichern",
        style: .default,
        handler: { (action: UIAlertAction!) -> Void in
            inputTextField = alertController.textFields![0]
            inputTextField?.text = text
    })

    let cancelAction = UIAlertAction(
        title: "Abbruch",
        style: .default,
        handler: { (action: UIAlertAction!) -> Void in
    })

    // Add the actions to the UIAlertController
    alertController.addAction(saveAction)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)

    return (inputTextField?.text)!
}

1 个答案:

答案 0 :(得分:2)

当执行此行inputTextField时,

return (inputTextField?.text)!为空。您要做的就是更改您的saveAction,然后从该操作中使用以下文本:

let saveAction = UIAlertAction(
    title: "Speichern",
    style: .default,
    handler: { (action: UIAlertAction!) -> Void in
        inputTextField = alertController.textFields![0]
        inputTextField?.text = text
        use(newText: text) //Or do whatever you want with the text
})

并声明使用该文本的函数:

func use(NewText: String) {
//Do whatever with the new text
}

并且无需从changeLabeltext返回字符串:

func changeLabeltext(text: String) {
//...
}