如何在Swift中使用字符串初始化NSTextStorage

Sur*_*gch 5 ios nstextstorage swift

为了将另一个问题分解成更小的部分,我试图设置所有的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))

        })
    }
}
Run Code Online (Sandbox Code Playgroud)

它崩溃enumerateLineFragmentsForGlyphRangeEXC_I386_GPFLT的异常代码.那段代码不是很解释.基本问题似乎归结为我如何初始化NSTextStorage.

如果我更换

let textStorage = NSTextStorage(string: "This is a test")
layoutManager.textStorage = textStorage
Run Code Online (Sandbox Code Playgroud)

有了这个

layoutManager.textStorage = textView.textStorage
Run Code Online (Sandbox Code Playgroud)

然后它工作.我究竟做错了什么?

jam*_*rez 7

这似乎是做事的方法,是将NSLayoutManager添加到NSTextStorage对象,(使用addLayoutManager :)而不是在布局管理器上设置textStorage属性.

来自Apple的文件:

将NSLayoutManager添加到NSTextStorage对象时,将自动调用此方法; 你永远不需要直接调用它,但你可能想要覆盖它.如果要为包含接收器的已建立的文本系统对象组替换NSTextStorage对象,请使用replaceTextStorage:.

链接到setTextStorage:用于NSLayoutManager

大概是在'addLayoutManager:'中完成了一些事情,这在setTextStorage中没有完成,导致崩溃.

您可能还希望增加textStorage变量的范围,如果它看起来在viewDidLoad完成后被清除.