【问题标题】:Swift make UILabel text bold in between custom identifierSwift 在自定义标识符之间使 UILabel 文本加粗
【发布时间】:2020-03-31 04:45:42
【问题描述】:

我有一个文本为

的 UILabel

This is not bold, -bold- this is bold, -/bold- and this is another not bold, -bold- this is another bold -/bold-.

现在,我想将文本中每个 -bold--/bold- 之间的文本字体更改为粗体,这样它就会变成这样

这不是粗体,这是粗体,这是另一个非粗体,这是另一个粗体

我该怎么做?

【问题讨论】:

    标签: swift string fonts uilabel bold


    【解决方案1】:

    您可以使用NSMutableAttributedString 并将其设置为UILabelattributedText 属性。

    let label = UILabel()
    //Choose your bold font
    let boldAttributes = [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 15)]
    let mutableAttributedString = NSMutableAttributedString()
    mutableAttributedString.append(NSAttributedString(string: "Non-bold text #1", attributes: nil))
    mutableAttributedString.append(NSAttributedString(string: "Bold text #1", attributes: boldAttributes))
    mutableAttributedString.append(NSAttributedString(string: "Non-bold text #2", attributes: nil))
    mutableAttributedString.append(NSAttributedString(string: "Bold text #2", attributes: boldAttributes))
    label.attributedText = mutableAttributedString
    

    【讨论】:

    • 但是给定的字符串会不时改变,它可以是some random -bold- string -/bold- and another -bold- randomised string -/bold-,所以我不能在函数中放置静态字符串。
    【解决方案2】:

    首先,获取分隔符内的字符串。

    let query = "This is not bold, -bold- this is bold, -/bold- and this is another not bold, -bold- this is another bold -/bold-"
    let regex = try! NSRegularExpression(pattern: "-bold- (.*?) -/bold-", options: [])
    var results = [String]()
    regex.enumerateMatches(in: query, options: [], range: NSMakeRange(0, query.utf16.count)) { result, flags, stop in
    
        if let r = result?.range(at: 1),
            let range = Range(r, in: query) {
            results.append(String(query[range]))
        }
    }
    
    print(results)
    

    接下来,创建一个字符串扩展方法,如下所示。

    extension String {
    
        func attributedString(with style: [NSAttributedString.Key: Any]? = nil,
                              and highlightedTextArray: [String],
                              with highlightedTextStyleArray: [[NSAttributedString.Key: Any]?]) -> NSAttributedString {
    
            let formattedString = NSMutableAttributedString(string: self, attributes: style)
            if highlightedTextArray.count != highlightedTextStyleArray.count {
                return formattedString
            }
    
            for (highlightedText, highlightedTextStyle) in zip(highlightedTextArray, highlightedTextStyleArray) {
                let highlightedTextRange: NSRange = (self as NSString).range(of: highlightedText as String)
                formattedString.setAttributes(highlightedTextStyle, range: highlightedTextRange)
            }
    
            return formattedString
        }
    }
    

    方法详情:

    • 第一个参数:要申请的字体样式和其他属性 完整的字符串。
    • 第二个参数:要应用新样式的字符串数组。
    • 第三个参数:要应用的新样式(在本例中为粗体)。
    • 返回结果属性字符串。

    最后,调用如下方法。

    let attributedText = query.attributedString(with: [.font: UIFont.systemFont(ofSize: 12.0, weight: .regular)],
                           and: results,
                           with: [[.font: UIFont.systemFont(ofSize: 12.0, weight: .bold)]])
    

    希望对你有帮助。

    【讨论】:

    • 你在 query.attributedString 上的最后一个参数不是一个数组,它给了我一个错误说 Contextual type '[[NSAttributedString.Key : Any]?]' cannot be used with dictionary literal 所以我把它改成 with: [[.font: UIFont.systemFont(ofSize: 12.0, weight: .bold)]] 之后我写了 label.attributedText = attributedText 和文本label 仍然是 query 变量的值。
    • 我更正了最后一个参数。请检查 results 数组是否包含应加粗的字符串列表。
    【解决方案3】:

    实施:

    NSMutableAttributedString 编写一个扩展并实现粗体和普通字符串的方法。

     extension NSMutableAttributedString {
    
    
        func bold(_ value:String) -> NSMutableAttributedString {
    
            let attributes:[NSAttributedString.Key : Any] = [.font : UIFont.boldSystemFont(ofSize: 15)]
    
            self.append(NSAttributedString(string: value, attributes:attributes))
            return self
        }
    
        func normal(_ value:String) -> NSMutableAttributedString {
    
            let attributes:[NSAttributedString.Key : Any] = [.font : UIFont.systemFont(ofSize: 15)]
    
            self.append(NSAttributedString(string: value, attributes:attributes))
            return self
        }
    }
    

    用法:

    textLabel.attributedText = NSMutableAttributedString().normal("This is not bold, ").bold("this is bold, ").normal("and this is another not bold, ").bold("this is another bold.")
    

    结果:

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多