iOS-文本视图的图像附件更改属性
我有一个iOS-文本视图的图像附件更改属性,ios,uiimage,uitextview,nstextattachment,Ios,Uiimage,Uitextview,Nstextattachment,我有一个UITextView,使用给定的属性描述如下: lazy var inputTextView: UITextView = { let tv = UITextView() tv.backgroundColor = .white tv.textContainerInset = UIEdgeInsetsMake(12, 12, 12, 12) // Posicionamento do texto let spacing = NSMutableParagraph
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
之前,一切正常
图像被插入到所需位置,但插入后会覆盖mytextView
属性
文本变小,颜色与我在声明中实现的属性不同
我附上如下图片:
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代码。要了解为什么会发生这种情况,请参阅这篇苹果文章 我建议在指定字符串范围时使用以下符号(取自此堆栈溢出答案:)
但是,如果没有看到您如何设置光标位置,我无法确定这是您问题的根源。[更新:感谢您更新问题以显示光标位置-我们最终到达了目的地,但对于其他人,请注意,在以这种方式设置光标位置(这很好)后,他将其递增1,这意味着我提到的关于Unicode标量与代码点的问题实际上就是问题].可能是这样的:海报上说图像使用“set”,问题是我没有为现有字符串设置属性,我最初设置了键入属性,它们按预期工作,但当我插入图像时,我丢失了属性,无法将其设置回原位。我相信你误解了我说的图像调用“set”的意思,所以本质上是的,您调用的是“set”,因为您最后调用了图像,这会覆盖您的属性。你不是直接叫它,而是间接叫它哇。谢谢你的解释。我会用设置光标的代码更新答案。嗯,那我错了!由于位置是由current cursor position函数设置的,所以应该可以。然后在插入图像后,我将光标增加1!啊,那可以。是的,通过增加1,您将增加一个标量位置,这可能与下一个unicode代码点不对应。Hmm。。不过我认为你是对的。插入图像后,设置光标位置的最佳方法是什么?计算文本范围,然后将光标重置到最后一个可用位置,就像我在插入之前所做的那样?
// 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))