本文共 1355 字,大约阅读时间需要 4 分钟。
最近项目再使用swift重构,遇到Range和NSRange转换的问题,这里记录下:
因为要使用NSRange,所以有了下面这段代码,将String转换为NSString后调用 range(of searchString: String) -> NSRange
这种处理方法其实就是使用到了OC的方法了
let textStr = "登陆及代表同意《用户协议》与《隐私政策》"//获取NSRangelet range = NSString(string: textStr).range(of: "《隐私政策》")
以下为其他转换方法:
extension String { //Range转换为NSRange func toNSRange(_ range: Range) -> NSRange { guard let from = range.lowerBound.samePosition(in: utf16), let to = range.upperBound.samePosition(in: utf16) else { return NSMakeRange(0, 0) } return NSMakeRange(utf16.distance(from: utf16.startIndex, to: from), utf16.distance(from: from, to: to)) } //NSRange转换为Range func toRange(_ range: NSRange) -> Range ? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else { return nil } guard let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil } guard let from = String.Index(from16, within: self) else { return nil } guard let to = String.Index(to16, within: self) else { return nil } return from ..< to } }
使用如下:
let textStr = "登陆及代表同意《用户协议》与《隐私政策》"//Range->NSRangelet nsrange = textStr.toNSRange(linkStr.range(of: "《隐私政策》")//NSRange->Rangelet range = textStr.toRange(nsrange)
转载地址:http://idsni.baihongyu.com/