我从DB内容中提取为字符串.使用方法,我从该字符串中提取最长的单词.
现在我想将整个字符串打印到文本标签,但是想要在字符串中突出显示不同颜色和文本样式的最长字.
我怎样才能做到这一点?我是否需要将字符串切成碎片 - 设置格式 - 然后将它们全部放在一起再放入标签之前?
或者还有其他(更好的)方式吗?
Mat*_*uch 24
如果你已经知道最长的单词,你必须得到字符串中该单词的范围.我更喜欢NSString方法rangeOfString:.
然后NSMutableAttributedString使用默认属性从字符串创建一个.最后,将突出显示属性应用于您之前想出的范围.
let longString = "Lorem ipsum dolor. VeryLongWord ipsum foobar"
let longestWord = "VeryLongWord"
let longestWordRange = (longString as NSString).rangeOfString(longestWord)
let attributedString = NSMutableAttributedString(string: longString, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(20)])
attributedString.setAttributes([NSFontAttributeName : UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName : UIColor.redColor()], range: longestWordRange)
label.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)
在我的操场上看起来像这样:

| 归档时间: |
|
| 查看次数: |
14219 次 |
| 最近记录: |