我有一个 UITableview
,它从数据库中获取数据并将其显示在 UILabel
中。我想将文本的一部分“...少读”设为粗体,同时保留文本的其余部分。下面的代码只是检查帖子是否超过 120 个字符,如果超过 120 个字符,那么我会附加“...Read Less”,我想将附加的语句加粗。现在我的整个帖子都是粗体,而不仅仅是附加的字符串,任何建议都很好
func HomeProfilePlaceTVC(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTVC", for: indexPath) as! HomeTVC
cell.post.tag = indexPath.row
if streamsModel.Posts[indexPath.row].count > 120 {
cell.post.text = String(streamsModel.Posts[indexPath.row]).appending(" ... Read Less")
cell.post.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
}
else {
cell.post.text = streamsModel.Posts[indexPath.row]
}
return cell
}
您可以像这样创建一个扩展。
extension String {
func attributedString(with style: [NSAttributedString.Key: Any]? = nil,
and highlightedText: String,
with highlightedTextStyle: [NSAttributedString.Key: Any]? = nil) -> NSAttributedString {
let formattedString = NSMutableAttributedString(string: self, attributes: style)
let highlightedTextRange: NSRange = (self as NSString).range(of: highlightedText as String)
formattedString.setAttributes(highlightedTextStyle, range: highlightedTextRange)
return formattedString
}
}
然后像这样调用这个方法,使中间的字符串成为粗体
let descriptionText = "This is a bold string"
let descriptionText = descriptionText.attributedString(with: [.font: UIFont.systemFont(ofSize: 12.0, weight: .regular),
.foregroundColor: .black],
and: "bold",
with: [.font: UIFont.systemFont(ofSize: 12.0, weight: .bold),
.foregroundColor: .black])
输出:“这是一个粗体字符串”。您可以将其设置为 UILabel,如下所示。
textLabel.attributedString = descriptionText
此方法可用于以不同样式(例如粗体、斜体等)突出显示整个字符串中的任何范围的文本。
如果这有帮助,请告诉我。