ios swift:是否可以改变string中某个单词的字体风格?

我从string中提取数据库内容。 用一个方法从这个string中提取最长的单词。

现在我想将整个string打印到文本标签,但是想要突出显示string中不同颜色和文本样式中最长的单词。

我怎样才能做到这一点? 是否需要将string切成小块 – 设置格式 – 然后再将它们放在标签中,然后再放在一起?

还是有其他更好的方法?

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

然后,使用默认属性从string中创build一个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 

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

在这里输入图像说明

你想看看Attributed Strings和NSRange。 您可以同时使用这两个来为string中的范围创build不同的样式。 这是一个片段:

 myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!]) //Add more attributes here: myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Chalkduster", size: 24.0), range: NSRange(location: 7,length: 5)) myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "AmericanTypewriter-Bold", size: 18.0)!, range: NSRange(location:2,length:4)) myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4)) myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Georgia", size: 36.0)!, range: NSRange(location: 0, length: 1)) myMutableString.addAttribute(NSStrokeColorAttributeName, value: UIColor.blueColor(), range: NSRange(location: 0, length: 1)) myMutableString.addAttribute(NSStrokeWidthAttributeName, value: 2, range: NSRange(location: 0, length: 1)) myMutableString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location: 0, length: myString.length)) myLabel.backgroundColor = UIColor.grayColor() //Apply to the label myLabel.attributedText = myMutableString 

NSMutableAttributedString。

你创build一个NSMutableAttributedString并应用你想要的效果addAttributes:range

然后将其分配给UILabelattributedText UILabel attributedText