警报不会按预期弹出

Alert doesn't pop up when expected

我想更改标签的文本。

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

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

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)!
}

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
}

并且不需要 return 来自 changeLabeltext 的字符串:

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