美文网首页OC-开发案例收集
Swift 中 Range 与 NSRange 的转换

Swift 中 Range 与 NSRange 的转换

作者: 夜月饮酒 | 来源:发表于2018-05-24 21:54 被阅读72次

写一段富文本

对字符串 "Have a nice day!",将单词 "nice" 用红色显示,其它字符用默认颜色。

分析

Swift 中依旧使用 NSAttributedString/NSMutableAttributedString 进行富文本的显示,它们在添加属性文本的时候接受的是 NSRange 类型的参数,这时就需要将 Range 变量转换为 NSRange 类型。

解决

let fullWord = "Have a nice day!"
let attrString = NSMutableAttributedString(string: fullWord)
let range = fullWord.range(of: "nice")!
let nsrange = NSRange(range, in: fullWord) // Range to NSRange
attrString.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.red], range: nsrange)
textLabel.attributedText = attrString

要点

取出 "nice" 在字符串中的位置

let range = fullWord.range(of: "nice") // Range 类型

NSRange 转 Range

let nsrange = NSRange(range, in: fullWord)

Range 转 NSRange

let range = Range(nsrange, in: fullWord)

相关文章

网友评论

    本文标题:Swift 中 Range 与 NSRange 的转换

    本文链接:https://www.haomeiwen.com/subject/uohejftx.html