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

标签 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 = 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/

相关文章:

ios - 将数据从 Parse tableview 传递到 WatchKit

iphone - 我可以为不同的应用程序提交相同的应用程序图标吗?

ios - 在 iOS 7 上纵向裁剪图像会导致方向不正确

ios - 使用 QuartzCore 为 UITextView 创建阴影

ios - 根据不同的设备设置UITextView字体大小

jQuery scrollTop 在 iOS 上的 iframe 中不起作用

ios - 没有 '..<' 候选人产生预期的上下文结果类型 'NSRange Swift 3

iphone - 如何使用 UIImageView 调整图片大小以便放大和缩小?

iphone - 如何使用 ASIHTTP 保持连接处于事件状态?我需要发出多个请求,但无法打开然后关闭请求连接

swift - 使用 uiTextView 关闭键盘