gpt4 book ai didi

iOS - TextView 的图像附件更改属性

转载 作者:行者123 更新时间:2023-11-29 00:19:38 25 4
gpt4 key购买 nike

我有一个 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
}

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

最佳答案

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

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

Strings in Swift 2

我建议在指定字符串范围时使用以下表示法(取自 Stack Overflow 答案:NSAttributedString and emojis: issue with positions 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 标量与代码点的问题实际上就是问题所在]。

关于iOS - TextView 的图像附件更改属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com