gpt4 book ai didi

swift - 如何将图像放在附加到 NSTextAttachment 类型的 textView 上?

转载 作者:行者123 更新时间:2023-11-28 07:32:15 25 4
gpt4 key购买 nike

我有一个 textView(以编程方式),我插入了一个附加到 NSTextAttachment 的图像,并希望它与 TextView 的中心对齐......但我还没有找到任何解决方案......我想知道如果该任务可以仅通过代码完成...

    let image = ResizeImage(image: UIImage(named: "logo")!, targetSize: size)

let image1Attachment = NSTextAttachment()

image1Attachment.image = image

let image1Attachments = NSAttributedString(attachment: image1Attachment)

我尝试实现这一目标的最佳解决方案是这段代码:

    let image = ResizeImage(image: UIImage(named: "telepaint1")!, 
targetSize: size)

//let textAttachment = NSTextAttachment()
let textAttachment = NSTextAttachment()
//let imageStyle = NSMutableParagraphStyle()
let imageStyle = NSMutableParagraphStyle()
//imageStyle.alignment = .center
imageStyle.alignment = .center
//textAttachment.image = image
textAttachment.image = image
let imageText = NSAttributedString(attachment:
textAttachment).mutableCopy() as! NSMutableAttributedString
//attempt to center image...
let attributedStringToAppend: NSMutableAttributedString =
NSMutableAttributedString(attributedString:
NSAttributedString(string: "\n\n"))

//attributedStringToAppend.addAttributes(attr, range: range)

let combination2: NSMutableAttributedString =
NSMutableAttributedString(attributedString:
NSAttributedString(string: "\n\n"))


combination2.append(lineBreak)
// combination2.addAttribute(attr, range: NSRange(location: 0,
length: length))

combination2.append(imageText)
//this text will display the "Walktrough" text on image

combination2.append(attributedText)

tv.attributedText = combination2

最佳答案

enter image description here答案(对我有用!):

    let paragraphStyle = NSMutableParagraphStyle()

paragraphStyle.alignment = .center

attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: length))

let size = CGSize(width: 100, height: 100)


//Here is an attempt to resize image and center it...



let image = ResizeImage(image: UIImage(named: "logo")!.withRenderingMode(.alwaysTemplate), targetSize: size)


let textAttachment = NSTextAttachment()


let imageStyle = NSMutableParagraphStyle()


imageStyle.alignment = .center


textAttachment.image = image


let imageText = NSAttributedString(attachment: textAttachment).mutableCopy() as! NSMutableAttributedString

let length2 = imageText.length

imageText.addAttribute(NSAttributedString.Key.paragraphStyle, value: imageStyle, range: NSRange(location: 0, length: length2))

关于swift - 如何将图像放在附加到 NSTextAttachment 类型的 textView 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54370235/

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