首页 > 解决方案 > 获取嵌入在 NSAttributedString 中的图像(通过 NSTextAttachment)被视为单个字符,这样它就不会断行?

问题描述

我在 NSAttributedString 中嵌入了一个图像,我希望 iOS 将它视为一个字符,它是它之前的单词的一部分,这样它就不会被打破到自己的行中。我在某个地方读到了应该是默认行为的地方,但在我的一生中,我无法让它发挥作用。这是我的代码(我正在插入这个属性字符串作为按钮的标题):

    var title = "This is an example string. Test testtt"
    let titleTextString = NSMutableAttributedString(string: title)

    let imageAttachment =  NSTextAttachment()
    imageAttachment.image = UIImage(named:"myIcon")
    imageAttachment.bounds = CGRect(x: 0, y: 1.0, width: 14, height: 6)
    let imageAttachmentString = NSMutableAttributedString(attachment: imageAttachment)


    titleTextString.append(imageAttachmentString)
    button.setAttributedTitle(titleTextString, for: .normal)

这是它的样子:

在此处输入图像描述

如您所见,字符串末尾没有空格。我试图让标签将文本附件视为正常的非空白字符,因此是单词“testtt”的一部分,这将导致“testtt”被自动换行(否则单词被正确地自动换行,并且我在标签和 NSAttributedString 的段落样式中都设置了自动换行)。

使这件事复杂化的是,我发现存在解决问题的非中断,但会迫使字符串的其他部分不必要地中断。如果我在字符串末尾附加一个不间断的空格:

var title = "这是一个示例字符串。测试 testtt" + "\u{A0}"

然后我得到了正确的破坏行为,但由于某种原因,前一个词也被不必要地破坏了:

在此处输入图像描述

有谁知道如何让这个行为正确(即,将图像视为任何其他字母,而不是空格?)

标签: iosswiftnsattributedstringnstextattachment

解决方案


您可以通过zero-width non-breaking space: \u{FEFF}在原始字符串的末尾添加 a 来完成此操作。

var title = "This is an example string. Test testtt\u{FEFF}"
let titleTextString = NSMutableAttributedString(string: title)

let imageAttachment =  NSTextAttachment()
imageAttachment.image = UIImage(named:"myIcon")
imageAttachment.bounds = CGRect(x: 0, y: 1.0, width: 14, height: 6)
let imageAttachmentString = NSMutableAttributedString(attachment: imageAttachment)


titleTextString.append(imageAttachmentString)
button.setAttributedTitle(titleTextString, for: .normal)

归功于这个 SO question+answer在 UILabel 中,是否可以强制一条线不在某个地方中断

编辑:

回答您关于错误换行的问题。你可以在这里找到答案。这是 Apple 引入的一种新的自动换行行为。


推荐阅读