iOS Swift可以使文字的特定部分变为粗体

时间:2019-04-12 03:00:40

标签: ios swift swift4

我有一个UITableview,它从数据库中获取数据,并将其显示在UILabel中。我想将“ ... Read Less”的部分文字加粗,而其余部分则保留。下面的代码只是检查帖子中是否包含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

}

1 个答案:

答案 0 :(得分:1)

您可以创建这样的扩展名。

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

此方法可用于突出显示整个字符串中具有不同样式(例如粗体,斜体等)的任意范围的文本。 请告诉我是否有帮助。

相关问题