UIAlertController上的文本字段触发禁用按钮

时间:2015-02-07 17:57:36

标签: ios swift

我有UIAlertController UITextField和提交按钮。代码如下所示:

let saveDialogue = UIAlertController(title: "Save Level",
    message: "",
    preferredStyle: .Alert)

let saveAction = UIAlertAction(title: "Save", style: .Default,
    handler: { (action) in
        let textfield = saveDialogue.textFields![0] as UITextField
        // do something with the textfield
    }
)
saveAction.enabled = false
saveDialogue.addTextFieldWithConfigurationHandler { (textField) in
    textField.placeholder = "My Level"
    textField.text = filename
    // conditionally enable the button 
    textField.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)

}

虽然无法点按该按钮,但点击键盘上的返回键会触发默认操作(saveAction)。

有解决方法吗?我还尝试验证处理程序中的textfield值,但视图将被取消。可以保留吗?

2 个答案:

答案 0 :(得分:5)

如果要忽略返回键输入,请设置textField的委托并在textFieldShouldReturn:委托方法中返回false。

喜欢吼叫:

saveDialogue.addTextFieldWithConfigurationHandler { (textField) in
    textField.placeholder = "My Level"
    textField.text = "hello"
    // conditionally enable the button
    textField.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)

    // Add this line
    textField.delegate = self
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    return false
}

答案 1 :(得分:0)

我确实解决了同样的问题。

//where alert is variable in class 
    override func textField(_ textField: UITextField,
                            shouldChangeCharactersIn range: NSRange,
                            replacementString string: String) -> Bool {
        if range.location >= 1 { return true } // if we have one or more characters

        guard let isTextFieldEmpty = textField.text?.isEmpty else { return true }

        if !isTextFieldEmpty {
            alert?.actions.first?.isEnabled = false
        } else {
            alert?.actions.first?.isEnabled = true
        }
        return true
    }