ios - 将UIView附加到UITextView

标签 ios swift uitextview

我想将自定义视图元素附加到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/

相关文章:

ios - 是否可以在从 iOS 端在设备上显示之前更改推送通知消息?

ios - 为什么 buttonName.removeFromSuperview 不总是删除按钮?

macos - 在 Swift 中使用 NSInputStream 从 STDIN 获取输入

swift - 用通用类覆盖等于

iphone - 用于检测电话号码和超链接的 UITextView 设置

ios - UITextView 禁用换行

ios - 如何从 SFSafariViewController 获取 URL?

ios - 无法使用类型为 'dataTaskWithRequest' 的参数列表调用 '(NSMutableURLRequest, (_, _, _) throws -> _)'

iphone - UITextView inside UIScrollView 滚动问题

ios - 重新加载节中的标题,而不用快速重新加载节行