如何更新 NSView 中的文本?

How to update a text within NSView?

我想更新通过 drawInRect: withAttributes: 添加到 NSView 的文本。但是,似乎无法仅通过更改 属性.

来更新文本
class MyView: NSView {
    var str: NSString!

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        str = "Sample Text"
        str.drawInRect(NSMakeRect(0, 0, 60, 40), withAttributes: nil)
    }
}

上面的代码为视图创建了文本 Sample Text,我将其添加到情节提要中。

但是,当我尝试通过更改 属性 或再次调用 drawInRect: withAttributes: 来更新文本时,文本根本没有更新。这是代码:

@IBAction func callButton(sender: AnyObject) {
        myView.str = "Test"
        myView.str.drawInRect(CGRectMake(0, 0, 60, 40), withAttributes: nil)
} 

为什么文字没有更新?另外,我该如何更新文本?

不要覆盖 drawRect 中的 str。相反,在初始化时将默认字符串设置为 属性,并在更新 str 属性.

时使用 setNeedsDisplay 将视图标记为脏