为了将
another problem分解成更小的部分,我试图设置所有的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)) }) } }
它在enumerateLineFragmentsForGlyphRange崩溃,异常代码为EXC_I386_GPFLT.该代码不是很解释.基本问题似乎归结为我如何初始化NSTextStorage.
如果我更换
let textStorage = NSTextStorage(string: "This is a test") layoutManager.textStorage = textStorage
有了这个
layoutManager.textStorage = textView.textStorage
然后它工作.我究竟做错了什么?
解决方法
这似乎是做事的方法,是将NSLayoutManager添加到NSTextStorage对象,(使用addLayoutManager :)而不是在布局管理器上设置textStorage属性.
来自Apple的文件:
This method is invoked automatically when you add an NSLayoutManager to an NSTextStorage object; you should never need to invoke it directly,but you might want to override it. If you want to replace the NSTextStorage object for an established group of text-system objects containing the receiver,use replaceTextStorage:.
Link to setTextStorage: for NSLayoutManager
大概是在’addLayoutManager:’中完成了一些事情,这在setTextStorage中没有完成,导致崩溃.
您可能还希望增加textStorage变量的范围,如果它看起来在viewDidLoad完成后被清除.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。