[绍棠_Swift] swift4.0 NSMutableAttributeString的Range和NSRange问题

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-23 06:34   165   0

Range是无法通过 as? 强制转换到NSRange的。

强制转换会crash Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1000b4488)

var mutableAttrStr = NSMutableAttributedString.init()

// range 不能用as? 强制转换

let substringRange = mutableAttrStr.string.range(of: friendModel.userName!)

friendModel.range = mutableAttrStr.string.nsRange(from: substringRange!)



//range转换为NSRange

//扩展的是String类,不可改为NSRange或者Range的扩展,因为samePosition,utf16是String里的

extension String {

func nsRange(from range: Range<String.Index>) -> NSRange {

let from = range.lowerBound.samePosition(in: utf16)

let to = range.upperBound.samePosition(in: utf16)

return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),

length: utf16.distance(from: from, to: to))

}

}


//NSRange转化为range

//扩展的是String类,不可改为NSRange或者Range的扩展,因为utf16是String里的

extension String {

func range(from nsRange: NSRange) -> Range<String.Index>? {

guard

let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),

let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),

let from = String.Index(from16, within: self),

let to = String.Index(to16, within: self)

else { return nil }

return from ..< to

}

}



分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP