ios - 将字符串添加到 NSMutableAttributedString 时出错

标签 ios iphone swift swift3 swift3.2

我有这个功能可以将项目符号添加到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
}

当向只有一行的段落插入项目符号时,它会起作用

bullet with just one single line

但是当我将它添加到具有多行的段落时,就会发生这种情况 bullet with more than one line

我希望它看起来像第一张图片中的那样,项目符号和文本开头没有空格

我也尝试过使用 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

这将导致预期的行为,其中非常长的字符串不会中断为自己的行,因为它将连接到前面的项目符号点:

textView

此外,如果项目符号和字符串之间的空格太小,只需将多个不间断空格串在一起即可:

let bullet = "●\u{00A0}\u{00A0}"

关于ios - 将字符串添加到 NSMutableAttributedString 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44529078/

相关文章:

iphone - 在后台播放视频

ios - 如何仅从 collectionView 的单元格中重新加载一项? swift 4

iphone - 从键盘处理 del 键

ios - GCD 并发队列未按 FIFO 顺序启动任务

iphone - 保护 Objective C 源代码中的敏感信息

iphone - iOS:如何使用下载的 CSV 填充 CoreData

ios - 如何在 SwiftUI 中实现类似 onAppear 的功能?

ios - 如何在 Swift 3 中将 Core Data 与 iCloud 同步

ios - 计时器不重复(Grand Central Dispatch)

swift - 无法推断复杂的闭包返回类型;在 RxSwift 中添加显式类型以消除歧义