以下は、NSTextStorage に基づく UITextView の簡単な例です。「doAction1」は、何らかの UI ボタンをクリックすると起動されます。ドキュメントを読んで、編集の開始/終了ブロックで NSTextStorage を更新すると、ビューも自動的に更新されるという印象を受けました。
ただし、それは起こらないようです。以下の例では、「...World!」が追加されています。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()
}
}