无法转换类型的价值&#39; NSRange&#39; (又名&#39; _NSRange&#39;)预期类型&#39;范围<索引>&#39;(又名&#39;范围<string.characterview.index>&#39;)

时间:2015-09-24 19:49:57

标签: ios swift nsrange

检查字符串字符的范围时出现此错误...

@objc func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let shouldChange = false
    let text = textField.text
    var newString = text!.stringByReplacingCharactersInRange(range, withString: string) as? NSString
    if newString.length > 14{
        newString = newString.substringToIndex(14)
    }
    textField.text = newString.uppercaseString

    return shouldChange
}

2 个答案:

答案 0 :(得分:33)

而不是text!(text! as NSString)

var newString = (text! as NSString).stringByReplacingCharactersInRange(range, withString: string) as? NSString

答案 1 :(得分:-1)

快捷键4

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

    if let oldString = textField.text {
        let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!,
                                                      with: string)
        // ...
    }
    // ...
}