gpt4 book ai didi

ios - 将UIView附加到UITextView

转载 作者:行者123 更新时间:2023-11-28 13:38:43 24 4
gpt4 key购买 nike

我想将自定义视图元素附加到UITextView。它需要很好地处理周围的文本,并允许它被选中和删除。这与Apple Notes中的inline image函数非常相似。
在Swift中实现这一点的代码是什么,我猜是NSTextAttachement
例子:
enter image description here

最佳答案

您的猜测是正确的,您可以使用NSTextAttachement将视图附加为图像,这是一个简单的逐步过程
渲染图像

let renderer = UIGraphicsImageRenderer(size: view.frame.size)
let image = renderer.image {
view.layer.render(in: $0.cgContext)
}

创建附件
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = CGRect(origin: .zero, size: image.size)

最后,插入附件
let currentAtStr = NSMutableAttributedString(attributedString: textView.attributedText)
let attachmentAtStr = NSAttributedString(attachment: attachment)
if let selectedRange = textView.selectedTextRange {
let cursorIndex = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
currentAtStr.insert(attachmentAtStr, at: cursorIndex)

// Workaround that causes different font after the attachment image, https://stackoverflow.com/questions/21742376
currentAtStr.addAttributes(textView.typingAttributes, range: NSRange(location: cursorIndex, length: 1))
} else {
currentAtStr.append(attachmentAtStr)
}
textView.attributedText = currentAtStr

关于ios - 将UIView附加到UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56301875/

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