iOS具有内置功能,用户可以在中设置文本替换
设置>常规>键盘>文本替换
在我的Swift iOS应用程序的UITextField中,我需要知道用户何时使用了这个文本替换,这样我才能采取适当的行动。我的本能是使用
func textField(tf: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
但有趣的是,这种文本替换并没有调用这个函数,有其他方法可以解决这个问题吗?
我在这个设置中测试了shouldChangeCharactersInRange
函数,它确实看到了文本扩展。我用测试
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
print(string.characters.count)
return true
}
您可以看到字符数在文本展开后立即跳跃。
确保您的textField与IBOutlet连接,并且您已将类设置为委托(viewDidLoad
中的textField.delegate = self
)。
一旦你看到这一点,你当然可以识别文本扩展,并以任何方式处理你想要的。