NSTextStorage支持的UITextView在附加文本时未更新

时间:2016-07-30 12:54:57

标签: ios swift uitextview core-text nstextstorage

以下是由NSTextStorage支持的UITextView的一个简单示例。通过单击某个UI按钮触发“doAction1”。通过阅读文档,我的印象是通过在开始/结束编辑块中更新NSTextStorage,View也会自动更新。

然而,它似乎没有发生 - 下面的例子附加“......世界!”到NSTextStorage但UITextView没有反映出 - 并继续只显示“Hello”。有什么想法吗?

import UIKit

class ViewController: UIViewController {
  let TEXT = "Hello"

  var m_layoutManager: NSLayoutManager!
  var      m_textView: UITextView!

  @IBAction func doAction1(_ sender: AnyObject) {
      let ts = m_layoutManager.textStorage

      ts?.beginEditing()
      ts?.append(AttributedString(string:"...World!"))
      ts?.endEditing()

      // These two don't make a difference either:
      //
      // m_layoutManager.invalidateDisplay(forCharacterRange: NSRange(location: 0, length: (ts?.length)!))
      // m_textView.setNeedsDisplay()
      //
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    let textStorage = NSTextStorage(string: TEXT)
    let textContainer = NSTextContainer(
        size: CGSize(width: 200, height: 300))

    m_layoutManager = NSLayoutManager()
    m_layoutManager.textStorage = textStorage
    m_layoutManager.addTextContainer(textContainer)

    m_textView = UITextView(
        frame: CGRect(x: 0, y: 20, width: 200, height: 300),
        textContainer: textContainer)

    view.addSubview(m_textView)
  }

  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
  }
}

1 个答案:

答案 0 :(得分:0)

解决。 NSLayoutManager未正确连接到NSTextStorage。因此,而不是告诉布局管理器它有一个存储,即:

m_layoutManager.textStorage = textStorage

我告诉存储它有一个经理:

textStorage.addLayoutManager(m_layoutManager)

就是这样。