为什么 NSAttributedString 格式化我的整个字符串?

Why does the NSAttributedString format the whole of my string?

我有一大段文字,看起来像这样:

使用此代码:

detail2TextView.text = textAnhorig.chapter12

文本样式设置为 iOS 的默认文本样式 body

使用代码,我成功地将引用的文本格式化为斜体。这是代码:

//function that format part of text
func formatfunc(chapter: String, boldStart: Int, boldLength: Int, italicsStart: Int, italicsLength: Int) -> NSAttributedString {
    let bold = UIFont.boldSystemFont(ofSize: 17)
    let italics = UIFont.italicSystemFont(ofSize: 17)

    let attributedString = NSMutableAttributedString.init(string: chapter)
    attributedString.addAttribute(.font, value: bold, range: NSRange.init(location: boldStart, length: boldLength))
    attributedString.addAttribute(.font, value: italics, range: NSRange.init(location: italicsStart, length: italicsLength))

    return attributedString
}

//calling function
let formated = textAnhorig.formatfunc(chapter: textAnhorig.chapter12, boldStart: 0, boldLength: 0, italicsStart: 0, italicsLength: 85)

//presenting edited text
detail2TextView.attributedText = formated

这工作正常,但问题是字符串的其余部分出于某种原因被格式化为完全不同的样式 - 更小并且可能使用另一种字体(无法真正分辨)。你可以在这里看到结果:

发生了什么,我该如何阻止它发生并保持文本的其余部分不变?

您应该先为整个字符串设置一个基本字体,然后将粗体和斜体应用到所需范围。

func formatfunc(chapter: String, boldStart: Int, boldLength: Int, italicsStart: Int, italicsLength: Int) -> NSAttributedString {
    let bold = UIFont.boldSystemFont(ofSize: 17)
    let italics = UIFont.italicSystemFont(ofSize: 17)

    let attributedString = NSMutableAttributedString(string: chapter, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)])
    attributedString.addAttribute(.font, value: bold, range: NSRange(location: boldStart, length: boldLength))
    attributedString.addAttribute(.font, value: italics, range: NSRange(location: italicsStart, length: italicsLength))

    return attributedString
}