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

时间:2018-09-28 23:35:49

标签: ios swift format nsattributedstring

我有很多这样的文字:

this使用以下代码:

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

这可以很好地工作,但是问题在于,由于某种原因,字符串的其余部分被格式化为完全不同的样式-较小,可能还有其他字体(无法真正分辨出)。您可以在这里查看结果:

here.

发生了什么,我如何阻止它发生,仅将其余文本保持原样?

1 个答案:

答案 0 :(得分:1)

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

old_coro_with_types()