如何转换 Range<String.Index>到 NSRange? [英] How to convert Range&lt;String.Index&gt; to NSRange?

查看:69
本文介绍了如何转换 Range<String.Index>到 NSRange?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift (<4) 中将 Range 转换为 NSRange 而不先将 String 转换为NSString?

How do I convert Range<String.Index> to NSRange in Swift (< 4) without first converting the String to an NSString?

我想这样做的原因是我想使用 Range 设置 UITextViewselectedText 属性> 价值.

The reason I want to do this is that I want to set a UITextView's selectedText property using a Range<String.Index> value.

替代解决方案:如何将 UITextInput.selectedTextRange 设置为 Range 值?

Alternative solution: How do I set UITextInput.selectedTextRange with a Range<String.Index> value?

推荐答案

在字符串的 UTF16 视图中使用 String.Index 的 samePosition(in:) 方法.NSString 使用 UTF16,因此 UTF16 索引应该与 NSString 期望的 NSRange 索引相同.

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.

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)
    }
}

这篇关于如何转换 Range<String.Index>到 NSRange?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆