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

标签 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 = "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/

相关文章:

ios - 关闭 UITableViewController 更改 ADBannerView 位置

ios - iOS URL方案或不存在的通用链接

json - 使用可编码的值,有时是 Int,有时是 String

ios - NSTextAttachment 的水平间距

ios - 一个 UITableViewCell 文本标签中的两种文本颜色

ios - RequestAuthorization 用于推送到 didFinishLaunchingWithOptions 之外

ios - 自定义字体在 iPad 5.0 和 5.1 上不起作用

objective-c - 操作系统 X : Saving open application states

ios - 将属性文本转换为HTML

ios - 利用 iOS 15 的英语字符串语法协议(protocol)功能