gpt4 book ai didi

ios - 如何对齐嵌入在 UITextView 中的图像

转载 作者:行者123 更新时间:2023-11-30 12:38:49 24 4
gpt4 key购买 nike

由于我的应用程序逻辑,我需要在 UITextView 中呈现一些带有图像的文本。嵌入图像不是问题(给出了工作解决方案,例如,此处 How to add image and text in UITextView in IOS? )。但我完全不知道如何对齐图像。我尝试设置属性

var attributedString: NSMutableAttributedString!
let textAttachment = NSTextAttachment()
let image = UIImage(named: imageName)

textAttachment.image = image
let attrStringWithImage = NSAttributedString(attachment: textAttachment)

let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.justified
let attrs = [NSParagraphStyleAttributeName: style]

attributedString = NSMutableAttributedString(attributedString: attrStringWithImage)
let text = NSAttributedString(string: myText, attributes: attrs)
attributedString.append(text)

myTextView?.attributedText = attributedString

但不影响图像。文本对齐得很好,但图像总是卡在 View 的左边缘。如何修复它?提前致谢。

最佳答案

var attributedString: NSMutableAttributedString!
let textAttachment = NSTextAttachment()
let image = UIImage(named: yourImage)

textAttachment.image = image

textAttachment.image = UIImage(cgImage: (textAttachment.image?.cgImage)!, scale: 20, orientation: UIImageOrientation.left)
let attrStringWithImage = NSAttributedString(attachment: textAttachment)

let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.justified
let attrs = [NSParagraphStyleAttributeName: style]

attributedString = NSMutableAttributedString(attributedString: attrStringWithImage)
let text = NSAttributedString(string: yourText, attributes: attrs)
attributedString.append(text)

txtView?.attributedText = attributedString

您可以使用此代码根据需要更改方向和比例。

关于ios - 如何对齐嵌入在 UITextView 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42508786/

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