IOS swift有没有办法使文本的特定部分加粗

标签 ios swift swift4

<分区>

我有一个 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

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

关于IOS swift有没有办法使文本的特定部分加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643869/

相关文章:

ios - View 快速显示其外部的 subview

swift - FireStore Swift 4 : How to get total count of all the documents inside a collection, 并获取每个文件的详细信息?

ios - 如何捕获自动布局约束冗余

ios - 相机胶卷中的文件发生更改时如何刷新 UIImagePickerController?

ios - iPad Retina 模型快速识别

ios - 在 Swift 中使用自定义模型将 CoreData 模型添加到现有项目的最佳方法

iOS - AVSpeechSynthesizer 暂停和继续说话问题

ios - 由于-5825,iPhone 屏幕录制无法保存

ios - UIView 即使在开始从 superview 中移除后也会重新出现

ios - 在 Swift 中搜索大型数组性能