问题
How do I convert Range<String.Index>
to NSRange
in Swift (< 4) without first converting the String
to an NSString
?
The reason I want to do this is that I want to set a UITextView
's selectedText
property using a Range<String.Index>
value.
Alternative solution: How do I set UITextInput.selectedTextRange
with a Range<String.Index>
value?
回答1:
Use String.Index's samePosition(in:) method with the string's UTF16 view. NSString uses UTF16, so the UTF16 indexes should be identical to the indexes NSString expects for the NSRange.
EDIT:
public extension NSRange {
private init(string: String, lowerBound: String.Index, upperBound: String.Index) {
let utf16 = string.utf16
let lowerBound = lowerBound.samePosition(in: utf16)
let location = utf16.distance(from: utf16.startIndex, to: lowerBound)
let length = utf16.distance(from: lowerBound, to: upperBound.samePosition(in: utf16))
self.init(location: location, length: length)
}
public init(range: Range<String.Index>, in string: String) {
self.init(string: string, lowerBound: range.lowerBound, upperBound: range.upperBound)
}
public init(range: ClosedRange<String.Index>, in string: String) {
self.init(string: string, lowerBound: range.lowerBound, upperBound: range.upperBound)
}
}
来源:https://stackoverflow.com/questions/45493826/how-to-convert-rangestring-index-to-nsrange