是否可以更改字符串中某个单词的字体样式

是否可以更改字符串中某个单词的字体样式

本文介绍了ios swift:是否可以更改字符串中某个单词的字体样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从DB内容中提取为字符串。使用方法,我从该字符串中提取最长的单词。

I am extracting from a DB contents as strings. With a method I extract the longest word out of this string.

现在我想将整个字符串打印成文本标签,但想在字符串中突出显示不同颜色和文本样式的最长字。

Now I would like to print out the entire string to a text label but would like to highlight the longest word in a different color and text style within the string.

我该怎么做?
我是否需要将字符串剪成碎片 - 设置格式 - 并在将它们放到标签之前将它们全部放在一起?

How can I do that?Do I need to cut the string into pieces - set the formatting - and put them all together again before giving it to the label?

或者还有其他(更好)方式吗?

Or is there any other (better) way?

推荐答案

如果你已经知道最长的单词,你必须得到字符串中该单词的范围。我更喜欢NSString方法 rangeOfString:

If you already know the longest word you have to get the range of that word in the string. I prefer the NSString method rangeOfString: for this.

然后使用默认属性从字符串创建 NSMutableAttributedString 。最后,将突出显示属性应用于您之前想出的范围。

You then create a NSMutableAttributedString from the string, with your default attributes. Finally you apply highlighting attributes to the range you figured out earlier.

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

在我的操场上看起来像这样:

Which looks like this in my playground:

这篇关于ios swift:是否可以更改字符串中某个单词的字体样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:02