我想将自定义视图元素附加到UITextView
。它需要很好地处理周围的文本,并允许它被选中和删除。这与Apple Notes中的inline image函数非常相似。
在Swift中实现这一点的代码是什么,我猜是NSTextAttachement
?
例子:
最佳答案
您的猜测是正确的,您可以使用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/