2016-11-22 1 views
0

shouldChangeCharactersInRange 메서드를 구현하면 범위 값과 텍스트 크기 사이에 일종의 불일치가 있습니다. 하나의 공백 문자 (예 : "a")가있는 텍스트 필드가 있고 백 스페이스 키를 누르면 교체 할 텍스트가 빈 문자열이고 textField.text!.characters.count은 1을 반환하고 분노는 0과 길이 1을 갖습니다. 텍스트 필드에 그림 이모티콘 (예 : '')이있는 경우 range.length은 1이 아닌 2를 반환하고, 이후에 NSRange에서 Range<String.Index>으로 캐스팅 할 때 충돌이 발생합니다. 왜 그렇게됩니까?shouldChangeCharactersInRange가 이모티콘으로 다른 범위를 제공합니다

+0

가능한 중복 문자열을 제공합니다 [NSRange 범위 ] (http://stackoverflow.com/questions/) 25138339/nsrange-rangestring-index) - 문자열과 NSString 범위가 다르므로 그 사이에 단순히 "캐스팅"할 수 없습니다. –

답변

1

스위프트 3.0

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

    guard let strtext = textField.text else { 
     return true } 

    let completeString = (strtext as NSString).replacingCharacters(in: range, with: string) 
    let increment = string == "" ? 0 : 1 

    let finalString = (completeString as NSString).substring(with: NSRange(location: 0, length: range.location + increment)) 

    print(finalString) 

    return true 
} 

참고 : -이 뜻이 커서 위치로 범위 시작 인덱스와의

관련 문제