Присоединить UIView к UITextView - PullRequest
0 голосов
/ 25 мая 2019

Я хочу прикрепить элемент пользовательского представления к UITextView. Он должен хорошо играть с окружающим текстом, а также позволять его выбирать и удалять. Это будет работать очень похоже на функцию встроенного изображения в Apple Notes.

Каков код для достижения этого в Swift, я думаю, NSTextAttachement?

Пример:

enter image description here

1 Ответ

1 голос
/ 25 мая 2019

Ваше предположение верно, вы можете использовать NSTextAttachement, чтобы прикрепить вид как изображение, простой пошаговый процесс

  1. Визуализация изображения

    let renderer = UIGraphicsImageRenderer(size: view.frame.size)
    let image = renderer.image {
        view.layer.render(in: $0.cgContext)
    }
    
  2. Создать вложение

    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(origin: .zero, size: image.size)
    
  3. Наконец, вставьте свое вложение

    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
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...