将 NSMutableAttributedString 应用于一系列文本

Applying NSMutableAttributedString to a range of text

我有一些文字:

New Content - Published Today | 10 min read

我想将样式应用于管道之后的所有内容,包括管道,所以 | 10 min read

我试过下面的方法,但它只有管道本身的样式。

  func makeAttributedText(using baseString: String?) -> NSMutableAttributedString? {
    guard let baseString = baseString else { return nil }
    let attributedString = NSMutableAttributedString(string: baseString, attributes: nil)
    let timeToReadRange = (attributedString.string as NSString).range(of: "|")
    attributedString.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)], range: timeToReadRange)
    return attributedString
  }

与其获取单个字符的 range,不如获取字符的 index 并创建从该索引到末尾的范围的字符串。

func makeAttributedText(using baseString: String?) -> NSMutableAttributedString? {
    guard let baseString = baseString else { return nil }
    let attributedString = NSMutableAttributedString(string: baseString, attributes: nil)
    guard let timeToReadIndex = baseString.firstIndex(of: "|") else { return attributedString }
    let timeToReadRange = NSRange(timeToReadIndex..., in: baseString)
    attributedString.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)], range: timeToReadRange)
    return attributedString
}

注:

Swift 有专门的方法将 Range<String.Index> 转换为 NSRange。没有理由将桥梁转换为 NSString