IOS swift 有没有办法将文本的特定部分设为粗体

IOS swift is there a way to make a specific portion of text bold

我有一个 UITableview 从数据库中获取数据,我将其显示在 UILabel 中。我想将文本的一部分“...少读”设为粗体,同时保留文本的其余部分。下面的代码只是检查 post 是否超过 120 个字符,如果是,那么我附加“ ... Read Less ”附加的语句我想加粗。现在我有整个 post 粗体,而不仅仅是附加的字符串,任何建议都很好

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])

输出:"This is a bold string"。您可以将其设置为 UILabel,如下所示。

 textLabel.attributedString = descriptionText

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