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

Ben*_*nMQ 1 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)

}
Run Code Online (Sandbox Code Playgroud)

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

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

kis*_*umi 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
}
Run Code Online (Sandbox Code Playgroud)

  • 我正在编写完全相同的答案,但你更快:)虽然更精确:我认为不是'return false`,他希望文本字段仅在启用提交按钮时验证(我猜它已启用/基于文本字段的内容禁用...). (2认同)