为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

iOS
人到中年有点甜 2019-11-12 10:59:18
我有这样的字符串var str = "@text1 this is good @text1"现在,text1用另一个字符串代替t 1。我可以替换文本,但不能将其加粗。我想将新字符串加粗t 1,这样最终输出将是:@t 1这很好@t 1我该怎么做?我看到的所有示例都在Objective-C中,但是我想在Swift中完成。提前致谢。
查看完整描述

3 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

如果您使用的是本地化字符串,则可能无法始终依靠粗体字符串作为句子的结尾。如果是这种情况,则可以很好地进行以下操作:


例如查询“ blah”与任何项目都不匹配


/* Create the search query part of the text, e.g. "blah". 

   The variable 'text' is just the value entered by  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

   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,

   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


查看完整回答
反对 回复 2019-11-12
  • 3 回答
  • 0 关注
  • 543 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信