简体   繁体   English

Swift Defer函数似乎不适用于textField委托shouldChangeCharactersIn

[英]Swift defer function doesn't seem to work with textField delegate shouldChangeCharactersIn

I'm running this code 我正在运行这段代码

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //does stuff
    defer {
        moveResponder(textField) // this assigns a new first responder after the character is input
    }
    return true

Defer is supposed to run after the function ends. Defer应该在函数结束后运行。 However, when I run this code the responder does indeed get moved to a new one and then the character change is implemented. 但是,当我运行这段代码时,响应者的确确实转移到了新的响应者,然后实现了字符更改。 I want it to be moved after the character is changed but the defer statement isn't working here as intended. 我希望在更改字符后将其移动,但是defer语句在这里无法按预期工作。 Am I missing something with this or do I need to try something else? 我是否缺少此功能,还是需要尝试其他操作?

Actually defer executes just before exiting the function… from the doc's 实际上, defer 退出函数之前执行…从文档的

A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in. 在将程序控制权转移到出现在defer语句出现的范围之外之前,将defer语句用于执行代码。

So, when you combine that with the UITextFieldDelegate method textField(_:shouldChangeCharactersIn:replacementString:) which is simply asking if the change should be allowed, it makes sense that the move occurs before the change is committed. 因此,当您将其与UITextFieldDelegate方法textField(_:shouldChangeCharactersIn:replacementString:)结合使用时,该方法只是询问是否允许进行更改,因此有意义的是该移动发生在提交更改之前。

If your conditions are met you should call textField.resignFirstResponder() then you can listen for the delegate method to call your function: 如果满足条件,则应调用textField.resignFirstResponder()然后可以侦听委托方法以调用函数:

optional func textFieldDidEndEditing(_ textField: UITextField) {
    moveResponder(textField)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM