Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

macos - Calling `print` inside NSView opens print dialog

This is bizarre. I have a simple storyboard placeholder with GridView for the class name attribute.

class GridView: NSView {

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        print("coder: (coder)")
    }

    override func drawRect(dirtyRect: NSRect) {
        let rect = NSBezierPath(rect: dirtyRect)
        NSColor.redColor().setFill()
        rect.fill()
    }
}

This worked as expected with just drawRect implemented, but after I added the initialiser it started opening the print dialog every time I run the app.

Print dialog

Why does this happen and how can I properly reimplement the storyboard initialiser for a custom view?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calling print() does something different as it should - more precisely: something different as you would expect. It calls NSView's print(sender: AnyObject?) instead of the logging print. You could consider this as a bug or at least as quite unexpected behavior since the Swift.print(...) is generally much more used.

This action method opens the Print panel, and if the user chooses an option other than canceling, prints the receiver and all its subviews to the device specified in the Print panel.

Take a look at this post in the apple dev forum.

In fact it is not a bug since calling the print which is "closer" in the current context is certainly the correct way. Calling the parent's print is a lot more reasonable than calling some arbitrary other print. Only the fact that you normally use the other print is the confusing point here since in general you do not worry in what scope the logging print is located - it just works. If you think the other way around and would want to use the printing print of your parent it would be a lot more confusing having to explicitly state that you want to use the parents print and not the Swift.print(...).

The only "solution" would be to use different names for the two functions which is probably not going to happen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...