我有这个功能可以将项目符号添加到textView
让项目符号:字符串=“●”
func setAttributedValueForBullets(bullet: String, positionWhereTheCursorIs: Int?) {
var textRange = selectedRange
let selectedText = NSMutableAttributedString(attributedString: attributedText)
if let line = positionWhereTheCursorIs {
textRange.location = line
}
selectedText.mutableString.replaceCharacters(in: textRange, with: bullet)
let paragraphStyle = createParagraphAttribute()
selectedText.addAttributes([NSParagraphStyleAttributeName: paragraphStyle], range: NSMakeRange(textRange.location, bullet.length))
self.attributedText = selectedText
self.selectedRange = textRange
}
当向只有一行的段落插入项目符号时,它会起作用
我希望它看起来像第一张图片中的那样,项目符号和文本开头没有空格
我也尝试过使用
selectedText.insert(bullet, at: textRange.location)
而不是
selectedText.addAttributes([NSParagraphStyleAttributeName:paragraphStyle],范围:NSMakeRange(textRange.location,bullet.length))
最佳答案
这本质上是由于要点和长描述之间的空白而发生的。如果描述太长,按照正常行为,它将继续到它自己的行,包裹字符串的其余部分。
最简单的解决方法是使用不间断的 unicode 空格字符 (u00A0):
let bullet = "●\u{00A0}"
let string = "thisisaveryveryveryveryveryveryveryveryveryverylongstring"
textView.text = bullet + string
这将导致预期的行为,其中非常长的字符串不会中断为自己的行,因为它将连接到前面的项目符号点:
此外,如果项目符号和字符串之间的空格太小,只需将多个不间断空格串在一起即可:
let bullet = "●\u{00A0}\u{00A0}"
关于ios - 将字符串添加到 NSMutableAttributedString 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44529078/