下面是一个由 NSTextStorage 支持的 UITextView 的简单示例。“doAction1”通过单击某个 UI 按钮触发。通读文档,我的印象是,通过在开始/结束编辑块中更新 NSTextStorage,视图也会自动更新自身。
然而,这似乎并没有发生——下面的例子附加了“......世界!” 到 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()
}
}