下面是一个由UITextView支持的NSTextStorage的简单示例。"doAction1“是通过单击某些UI按钮来触发的。通过阅读文档,我的印象是,通过更新开始/结束编辑块中的NSTextStorage,视图也会自动更新自己。
然而,这种情况似乎并没有发生--下面的例子是"...World!“但是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()
}
}发布于 2016-07-31 06:07:51
解决了。NSLayoutManager没有正确地连接到NSTextStorage。所以,不要告诉布局管理器它有一个存储,即:
m_layoutManager.textStorage = textStorage我告诉仓库有个经理:
textStorage.addLayoutManager(m_layoutManager)就是这样。
https://stackoverflow.com/questions/38674198
复制相似问题