簡體   English   中英

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

[英]How to Initialize NSTextStorage with a String in 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))

        })
    }
}

它在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的文件:

將NSLayoutManager添加到NSTextStorage對象時,將自動調用此方法; 你永遠不需要直接調用它,但你可能想要覆蓋它。 如果要為包含接收器的已建立的文本系統對象組替換NSTextStorage對象,請使用replaceTextStorage:。

鏈接到setTextStorage:用於NSLayoutManager

大概是在'addLayoutManager:'中完成了一些事情,這在setTextStorage中沒有完成,導致崩潰。

您可能還希望增加textStorage變量的范圍,如果它看起來在viewDidLoad完成后被清除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM