获取嵌入到NSAttributedString中的图像(通过NSTextAttachment)被视为单个字符,这样它就不会断行?

时间:2019-05-09 18:14:22

标签: ios swift 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)

这是它的外观图像:

enter image description here

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

使这个问题复杂化的原因是,我发现存在一个不间断的字符串,可以解决问题,但是会强制不必要地破坏字符串的其他部分。如果我在字符串末尾附加一个不间断空格:

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

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

enter image description here

有人知道如何正确执行此操作(例如,将图片视为其他字母,而不是空格吗?)

2 个答案:

答案 0 :(得分:2)

您可以通过在原始字符串的末尾添加zero-width non-breaking space: \u{FEFF}来实现。

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问题+解答In a UILabel, is it possible to force a line NOT to break in a certain place

的信用

编辑:

回答有关包裹错误单词的问题。您可以找到答案here。这是Apple引入的自动换行行为。

答案 1 :(得分:0)

enter image description here

将按钮标题标签文本lineBreakMode设置为.byWordWrapping,将textAlignment设置为.center,以获取方面的输出,请参见以下代码。

let 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: 7)
let imageAttachmentString = NSMutableAttributedString(attachment: imageAttachment)


titleTextString.append(imageAttachmentString)
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setAttributedTitle(titleTextString, for: .normal)