简体   繁体   中英

Simple Cocoa modal window dialog on Mac OS X

I am porting a plug-in from 32-bit to 64-bit which is actually in C++. Since Carbon is no longer supported on 64-bit, I have to port some code to Cocoa . The only Cocoa help I need is how to create a simple modal window (not a sheet) that has two buttons, OK and Cancel, and gives me a string input from the user. I created a Cocoa nib, but have no clue with Objective-C. I could start learning Objective-C right now, but it takes a while and that's the only code snippet I need right now.

What would the code snippet look like?

如果仅此而已,您可以使用CFUserNotification API来避免使用Cocoa。

You will need to learn some Objective-C and Cocoa regardless of what else you want to do, because there isn't "one system level call" to present a modal panel.

At minimum, you will need to create an NSWindowController subclass for your panel, which will act as File's Owner of its nib file and manage the interaction between its controls and whatever data it's manipulating. Then you'll need to pass this to -[NSApplication runModalForWindow:] and handle the result, or to -[NSApplication beginModalSessionForWindow:] and handle running and/or stopping the modal session yourself.

This means writing coding against the Cocoa frameworks in Objective-C.

Fortunately, since you're just starting with a message, a text field, and a couple of buttons, this will be pretty easy. But it's not just a matter of a hypothetical NSGetTextInput() function — Cocoa eschews such things in favor of abstractions that can be pieced together in straightforward and extensible ways.

For example, if you decide you don't just need text input but also a checkbox, you'd have to replace your hypothetical NSGetTextInput() with something like the above. But by doing the above in the first place, adding that checkbox becomes a few seconds of extra work. Or adding interesting validation to your text input. Or pre-populating your text input with data from an object. Or implementing a time-out (including presenting a countdown timer) on your modal dialog. (Modality is strongly disfavored nowadays...) Or any of a number of other changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM