附加文本时未更新的NSTextStorage支持的UITextView
问题描述:
以下是由NSTextStorage支持的UITextView的简单示例。点击某个UI按钮可激发“doAction1”。通过阅读文档,我的印象是,通过在开始/结束编辑块中更新NSTextStorage,View也会自动更新。附加文本时未更新的NSTextStorage支持的UITextView
但是,它似乎并没有发生 - 下面的例子附加“...世界!”到NSTextStorage,但UITextView并没有反映 - 并继续显示“你好”。任何想法?
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()
}
}
答
已解决。 NSLayoutManager未正确连接到NSTextStorage。所以,你不要告诉布局管理器,它具有存储,即:
m_layoutManager.textStorage = textStorage
我告诉它有一个管理器的存储:
textStorage.addLayoutManager(m_layoutManager)
就是这样。