【问题标题】:Swift 3.1 UITextField Type 'String.Index' (aka 'String.CharacterView.Index') does not conform to protocol '_Strideable'Swift 3.1 UITextField 类型“String.Index”(又名“String.CharacterView.Index”)不符合协议“_Strideable”
【发布时间】:2017-12-24 18:55:46
【问题描述】:
我已经实现了一个 uitextfield 委托方法 textFieldToChange 以只允许文本字段中的某些字符。最近我将我的应用程序更新到了 swift 3.1,现在我收到了 Type 'String.Index' (aka 'String.CharacterView.Index') does not conform to protocol '_Strideable' 错误。我正在附上我的代码快照:
请帮我解决这个问题。谢谢
【问题讨论】:
标签:
ios
swift3
uitextfield
【解决方案1】:
我最近遇到了同样的问题,对我有用的解决方案是检查是否没有字符与我的允许字符的反转集匹配,而不是检查所有字符是否与允许的字符集匹配。下面的代码对我来说非常有效。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacterSet = CharacterSet.letters
if string.isEmpty {
return true
} else if string.rangeOfCharacter(from: allowedCharacterSet.inverted) != nil { //check if the input contains anything else than letters
return false
} else {
return true
}
}