为了将另一个问题分解成更小的部分,我正在尝试设置所有 TextKit 组件。但是,在更改了我的初始化方式后我遇到了崩溃NSTextStorage
。出于测试目的,我将项目简化为以下内容:
import UIKit
class ViewController3: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var myTextView: MyTextView!
override func viewDidLoad() {
super.viewDidLoad()
let container = NSTextContainer(size: myTextView.bounds.size)
let layoutManager = NSLayoutManager()
let textStorage = NSTextStorage(string: "This is a test")
layoutManager.addTextContainer(container)
//layoutManager.textStorage = textView.textStorage // This works
layoutManager.textStorage = textStorage // This doesn't work
myTextView.layoutManager = layoutManager
}
}
class MyTextView: UIView {
var layoutManager: NSLayoutManager?
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext();
// Enumerate all the line fragments in the text
layoutManager?.enumerateLineFragmentsForGlyphRange(NSMakeRange(0, layoutManager!.numberOfGlyphs), usingBlock: {
(lineRect: CGRect, usedRect: CGRect, textContainer: NSTextContainer!, glyphRange: NSRange, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
// Draw the line fragment
self.layoutManager?.drawGlyphsForGlyphRange(glyphRange, atPoint: CGPointMake(0, 0))
})
}
}
它以EXC_I386_GPFLTenumerateLineFragmentsForGlyphRange
的异常代码崩溃。该代码不是很容易解释。基本问题似乎归结为我的初始化方式。NSTextStorage
如果我更换
let textStorage = NSTextStorage(string: "This is a test")
layoutManager.textStorage = textStorage
有了这个
layoutManager.textStorage = textView.textStorage
然后它工作。我究竟做错了什么?