猿问

快速使用属性字符串使文本加粗

我有这样的字符串


var str = "@text1 this is good @text1"

现在,text1用另一个字符串代替t 1。我可以替换文本,但不能将其加粗。我想将新字符串加粗t 1,这样最终输出将是:


@t 1这很好@t 1


我该怎么做?


我看到的所有示例都在Objective-C中,但是我想在Swift中完成。


提前致谢。


人到中年有点甜
浏览 581回答 3
3回答

皈依舞

如果您使用的是本地化字符串,则可能无法始终依靠粗体字符串作为句子的结尾。如果是这种情况,则可以很好地进行以下操作:例如查询“ blah”与任何项目都不匹配/* Create the search query part of the text, e.g. "blah".&nbsp;&nbsp; &nbsp;The variable 'text' is just the value entered by&nbsp; the user. */let searchQuery = "\"\(text)\""/* Put the search text into the message */let message = "Query \(searchQuery). does not match any items"/* Find the position of the search string. Cast to NSString as we want&nbsp; &nbsp;range to be of type NSRange, not Swift's Range<Index> */let range = (message as NSString).rangeOfString(searchQuery)/* Make the text at the given range bold. Rather than hard-coding a text size,&nbsp; &nbsp;Use the text size configured in Interface Builder. */let attributedString = NSMutableAttributedString(string: message)attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(label.font.pointSize), range: range)/* Put the text in a label */label.attributedText = attributedString
随时随地看视频慕课网APP

相关分类

iOS
我要回答