iOS-文本视图的图像附件更改属性



我有一个UITextView所描述的,如下所示:

lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.backgroundColor = .white
    tv.textContainerInset = UIEdgeInsetsMake(12, 12, 12, 12) // Posicionamento do texto
    let spacing = NSMutableParagraphStyle()
    spacing.lineSpacing = 4
    let attr = [NSParagraphStyleAttributeName : spacing, NSFontAttributeName: UIFont.systemFont(ofSize: 16),        NSForegroundColorAttributeName: UIColor.blue]
    tv.typingAttributes = attr
    return tv
}()

一切都按预期工作,直到我将图像连接到UITextView

图像被插入所需的位置,但是将其插入后覆盖了我的textView属性。

文本变小,颜色与我在声明中实现的属性不同。

我将图像附加如下:

    let att = NSTextAttachment()
    att.image = image
    let attrString = NSAttributedString(attachment: att)
    self.inputTextView.textStorage.insert(attrString, at: self.currentCursorLocation)

是什么原因导致了这个问题?

每当我将UIImage插入其内容时,我什至尝试重新强调其属性。

添加图像时我尝试了以下内容:

    let att = NSTextAttachment()
    att.image = image
    let attrString = NSAttributedString(attachment: att)
    self.inputTextView.textStorage.insert(attrString, at: self.currentCursorLocation)
    let spacing = NSMutableParagraphStyle()
    spacing.lineSpacing = 4
    let attr = [NSParagraphStyleAttributeName : spacing, NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor.blue]
    self.inputTextView.typingAttributes = attr

它仍然不会改变其属性。

是什么原因导致了这个问题?有小费吗?

谢谢

编辑

所建议的是我如何设置光标位置

func textViewDidChange(_ textView: UITextView) {
    currentCursorLocation = textView.selectedRange.location
}

我这样做是为了将图像插入文本闪烁光标的当前位置

[编辑:不幸的是,这不能解决伊万的问题 - 我留下答案,因为对于那些不了解Unicode字符编码的人来说,这是有趣的细节]。

字符串范围规范由于Unicode的微妙而非直觉。我希望您的问题是,您要插入图像的光标位置不是您认为它是相对于文本的位置,而是在Unicode代码点之间的Unicode标量位置上插入图像,以使您成为您的位置损坏Unicode代码。要了解为什么会发生这种情况,请参阅此Apple文章。

swift 2

中的字符串

我建议在指定字符串范围时使用以下符号(取自此堆栈溢出答案:nsattribedstring和emojis:具有位置和长度的问题(。

// Convert to NSRange by computing the integer distances:
let nsRange = NSRange(location: text.utf16.distance(from: text.utf16.startIndex, to: from16),
                      length: text.utf16.distance(from: from16, to: to16))

但是,没有看到您如何设置光标位置,因此我不可能确保这是您的问题的根源。[更新:感谢您更新问题以显示光标位置 - 我们最终到达那里,但对于其他人,请注意,在以这种方式设置光标位置(这本来可以很好(之后,他将其递增1,这是指我提到的有关Unicode标量与代码点的问题实际上是问题]。