gpt4 book ai didi

ios - 将嵌入 NSAttributedString(通过 NSTextAttachment)的图像视为单个字符,这样它就不会断行?

转载 作者:搜寻专家 更新时间:2023-10-31 08:03:37 25 4
gpt4 key购买 nike

我在 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 = "This is an example string. Test testtt"+ "\u{A0}"

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

enter image description here

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

最佳答案

您可以通过在原始字符串的末尾添加一个零宽度不间断空格:\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 引入的一种新的自动换行行为。

关于ios - 将嵌入 NSAttributedString(通过 NSTextAttachment)的图像视为单个字符,这样它就不会断行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56065339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com