ios - 调用文本字段 :shouldReplaceCharactersInRange from a delegate method

标签 ios swift uitextfield uikit

我构建了一个自定义屏幕键盘,每次按键都会返回一个 String?。在我的委托(delegate)方法中,我想将该文本转发到 UITextFieldDelegate 方法:func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

func valueWasSent(string: String?) {
    // activeTextField is a UITextField?
    guard let textField = activeTextField else { return }

    let range = NSMakeRange(0, string!.count - 1)
    textField(activeTextField!, shouldChangeCharactersIn: range, replacementString: string!)
}

这里的最后一行不工作,并抛出错误:

Cannot call value of non-function type 'UITextField'

知道如何实现吗?谢谢

最佳答案

您很可能不应该自己调用该委托(delegate)方法。 shouldChangeCharactersIn 只是检查编辑是否有效。通常,UITextField 会调用它来确保提议的更改是否有效。如果不是,则忽略更改。如果是,则更新文本字段的文本。

如果你真的想调用它,那么你需要在委托(delegate)上调用它,而不是self。您需要检查返回值。如果它返回 true,那么您应该相应地更新文本字段的文本。

if textField.delegate?.textField(textField, shouldChangeCharactersIn: range, replacementString: string!) {
    // update the text field's text
}

另请注意,您传递给它的范围应反射(reflect)文本字段中的当前选择。您正在将其设置为匹配 string 的长度。那很糟。如果您希望 string 完全替换当前值,至少传入一个与文本字段的当前值相匹配的范围,而不是 string

关于ios - 调用文本字段 :shouldReplaceCharactersInRange from a delegate method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48100487/

相关文章:

ios - 文本字段一侧的 UITextfield borderColor 和宽度

ios - React Native - RCTFatalException : Unhandled JS Exception: "version" is a required argument

ios - UITextField 只有顶部和底部边框

ios - 引用 dns_sd.h 中的 DNSSDObjects 和 MonoTouch 中的 DNSServiceResolve

ios - 从选择器中获取选定的项目 | swift 用户界面

iOS Swift 给出错误 : Garbage at end when serializing data from json

ios - `willPresent notification` 是 't called & local notifications aren' t 当应用程序在 iOS 10 中处于前台时不显示

iphone - 下一个按钮不浏览 UITextField

IOS 11 - 当另一个 pin 落后时,MKMapView pin 对话框不可点击

ios - 无法获取tableView的contentOffset