0

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
}

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

4

1 回答 1

1

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

由于 Unicode 的微妙之处,字符串范围规范是不直观的。我希望您的问题是您插入图像的光标位置不是您认为它相对于文本的位置,并且您将图像插入到不在 Unicode 代码点之间的 Unicode 标量位置,这样您就是破坏 unicode 代码。要了解为什么会发生这种情况,请参阅这篇 Apple 文章。

Swift 2 中的字符串

我建议在指定字符串范围时使用以下符号(取自这个 Stack Overflow 答案:NSAttributedString and emojis: issue with position and lengths)。

// 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 标量与代码点的问题实际上是问题]。

于 2017-06-07T19:20:09.257 回答