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

标签 ios swift

由于我的应用程序逻辑,我需要在 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/

相关文章:

ios - 使用AudioUnitSetParameter

ios - CSS 固定位置 Div 在 iOS 上随页面滚动然后返回到正确位置

objective-c - 在访问Objective C属性时可以具有参数吗?

ios - 动画期间 View Controller 中的中心图像

ios - 使用 Firebase 的内存泄漏

ios - self.window 在 View Controller 中不起作用

iOS 键盘动画冲突

json - 如果 JSON 答案为空,如何防止应用程序崩溃?

ios - 在 setRegion 上取消选择 MKAnnotationView

ios - 如何在 swiftui 中添加填充而不是边距