source: trunk/source/examples/cocoa/ui-elements/HOWTO.html @ 8559

Last change on this file since 8559 was 8559, checked in by mikel, 13 years ago

edits to button section of UI HOWTO

File size: 13.0 KB
Line 
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3<html xmlns="http://www.w3.org/1999/xhtml">
4  <head>
5    <title>UI Elements HOWTO</title>
6    <link rel="stylesheet" type="text/css" href="HOWTO_files/stylesheets/styles.css" />
7  </head>
8
9  <body>
10
11    <div class="title">
12      <h1>UI Elements HOWTO</h1>
13    </div>
14
15    <div class="body-text">
16      <p>This HOWTO shows how you can create Cocoa user-interface
17      elements by making lisp calls to instantiate and initialize
18      Objective-C objects.</p>
19
20      <p>Cocoa programmers usually create UI elements using Apple's
21      InterfaceBuilder application, and then load those elements from
22      a <strong>nibfile</strong>, but Cocoa supports creating all the
23      same UI elements by making Objective-C method calls. In fact,
24      that's how it loads nibfiles: by making method calls to
25      instantiate the objects described in them.</p>
26
27      <p>For Lisp programmers, accustomed to working incrementally and
28      interactively, it may sometimes make more sense to create
29      user-interface elements by making method calls interactively,
30      rather than by constructing a complete user interface in
31      InterfaceBuilder. This HOWTO shows how you can use Objective-C
32      method calls to create and display windows and other UI
33      elements.</p>
34
35      <p>For more information about how to load nibfiles from Lisp,
36      see the "nib-loading" example. For a complete discussion of how
37      to construct a Cocoa application using nibfiles created with
38      InterfaceBuilder, see the "currency-converter" example.</p>
39
40    <div class="title">
41      <h2>Creating a Window</h2>
42    </div>
43
44    <p>Every user-interface element under Mac OS X appears either in
45    a window or in a menu. We'll begin by exploring how to create and
46    display windows.</p>
47
48    <p>First, switch to the <code>CCL</code> package, for
49    convenience. Most of Clozure CL's Objective-C utilities are in
50    the <code>CCL</code> package:</p>
51
52    <pre>
53? (in-package :ccl)
54#&lt;Package "CCL"&gt;
55    </pre>
56
57    <p>Creating a Cocoa window follows the common Objective-C pattern
58    of allocating an object and then initializing it with some
59    starting data. To allocate a window, just call
60    the <code>alloc</code> method of the <code>NSWindow</code>
61    class:</p>
62
63    <pre>
64? (setf my-window (#/alloc (@class ns-window)))
65#&lt;NS-WINDOW &lt;NSWindow: 0x13b68580&gt; (#x13B68580)&gt;
66    </pre>
67
68    <p>The above expression creates a new window, but doesn't display
69    it. Before it shows up on the screen we must initialize it with
70    some appropriate values. For that, we'll use the
71    method <code>initWithContentRect:styleMask:backing:defer:</code>.</p>
72
73    <p>As always in Objective-C, the name of the method reveals
74    something about the arguments it expects. The <code>NSRect</code>
75    that we pass for the <code>initWithContentRect:</code> segment of
76    the method name describes the shape of the window. The mask
77    for <code>styleMask:</code> is a sequence of bits that specify
78    which window features are turned on. The <code>backing:</code>
79    argument is a constant of type <code>NSBackingStoreType</code>
80    that specifies how Cocoa will draw the contents of the
81    window. Finally, the <code>defer:</code> argument is a Boolean
82    that determines whether to display the window as soon as it's
83    created.</p>
84
85    <p>Next, we'll create data values to pass in these parameters, so
86    that we can display our new window on the screen. We'll build the
87    proper initialization form up piece-by-piece.</p>
88
89    <p>The first argument, of course, is the window object to be
90    initialized. We pass the window that we created before:</p>
91
92    <pre>
93(#/initWithContentRect:styleMask:backing:defer: my-window ...)
94    </pre>
95
96    <p>The next argument, the <code>NSRect</code>, is a structure
97    that we need only temporarily. Because <code>NSRect</code> values
98    appear so often in Cocoa code, Clozure CL provides a handy way to
99    allocate them temporarily, disposing of them
100    automatically. The <code>with-ns-rect</code> macro (in
101    the <code>NS</code> package) creates an <code>NSRect</code> value,
102    and then disposes of it when control leaves the scope of the
103    macro; for example:</p>
104
105    <pre>
106(ns:with-ns-rect (r 100 100 400 300)
107   ...)
108    </pre>
109
110    <p>We can use this rectangle to initialize the shape of our new
111    window:</p>
112
113    <pre>
114(ns:with-ns-rect (r 100 100 400 300)
115   (#/initWithContentRect:styleMask:backing:defer:
116    my-window
117    r
118    ...))
119    </pre>
120
121    <p>To specify the window features we want, we must combine
122    several flags to form the proper style mask. Cocoa provides named
123    constants for each of the various window features. To create the
124    syle mask that describes a new window, use inclusive-or to
125    combine the named flags into a style mask:</p>
126
127    <pre>
128(logior  #$NSTitledWindowMask
129         #$NSClosableWindowMask 
130         #$NSMiniaturizableWindowMask
131         #$NSResizableWindowMask)
132    </pre>
133
134    <p>You can find definitions for all the window masks in the Apple
135    Developer documentation
136    for <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWindow_Class/Reference/Reference.html#//apple_ref/doc/uid/20000013-89097">NSWindow
137    Constants</a>.</p>
138
139    <p>Passing the window mask as the next argument gives us this
140    expression:</p>
141
142    <pre>
143(ns:with-ns-rect (r 100 100 400 300)
144  (#/initWithContentRect:styleMask:backing:defer:
145   my-window
146   r
147   (logior  #$NSTitledWindowMask
148            #$NSClosableWindowMask 
149            #$NSMiniaturizableWindowMask
150            #$NSResizableWindowMask)
151   ...))
152    </pre>
153
154    <p>Like the style masks, the <code>NSBackingStoreType</code> value
155    is a named constant that describes which drawing strategy Cocoa
156    should use for the contents of the window. The value can
157    be <code>NSBackingStoreRetained</code>, <code>NSBackingStoreNonretained</code>,
158    or <code>NSBackingStoreBuffered</code>. For this example, we'll
159    use <code>NSBackingStoreBuffered</code>:</p>
160
161    <pre>
162(ns:with-ns-rect (r 100 100 400 300)
163  (#/initWithContentRect:styleMask:backing:defer:
164   my-window
165   r
166   (logior  #$NSTitledWindowMask
167            #$NSClosableWindowMask 
168            #$NSMiniaturizableWindowMask
169            #$NSResizableWindowMask)
170   #$NSBackingStoreBuffered
171   ...))
172    </pre>
173
174    <p>Finally, the <code>defer</code> argument is just a Boolean. If
175    we pass a true value, Cocoa will defer displaying the window until
176    we explicitly tell it to. If we pass a False value, it will
177    instead display the window right away. We can pass the Lisp
178    values <code>T</code> or <code>NIL</code>, and the Objective-C
179    bridge automatically converts them for us, but in the spirit of
180    using Objective-C values for Objective-C operations, let's use the
181    Objective-C constants <code>#$YES</code>
182    and <code>#$NO</code>:</p>
183
184    <pre>
185(ns:with-ns-rect (r 100 100 400 300)
186  (#/initWithContentRect:styleMask:backing:defer:
187   my-window
188   r
189   (logior  #$NSTitledWindowMask
190            #$NSClosableWindowMask 
191            #$NSMiniaturizableWindowMask
192            #$NSResizableWindowMask)
193   #$NSBackingStoreBuffered
194   #$NO))
195    </pre>
196
197    <p>There; the expression to initialize our window object is
198    finally complete. We can evaluate it in the Listener to
199    initialize the window:</p>
200
201    <pre>
202(ns:with-ns-rect (r 100 100 400 300)
203  (#/initWithContentRect:styleMask:backing:defer:
204   my-window
205   r
206   (logior  #$NSTitledWindowMask
207            #$NSClosableWindowMask 
208            #$NSMiniaturizableWindowMask
209            #$NSResizableWindowMask)
210   #$NSBackingStoreBuffered
211   #$NO))
212    </pre>
213
214    <p>Then we can call <code>makeKeyAndOrderFront:</code> to display the window:</p>
215
216    <pre>
217(#/makeKeyAndOrderFront: my-window nil)
218    </pre>
219
220    <p>The window, empty, but with the shape and features we
221    specified, appears on the left lower corner of the screen.</p>
222
223    <div class="title">
224      <h2>Adding a Button</h2>
225    </div>
226
227    <p>Once we have a window on the screen, we might like to put
228    something in it. Let's start by adding a button.</p>
229
230    <p>Creating a button object is as simple as creating a window
231    object; we simply allocate one:</p>
232
233    <pre>
234(setf my-button (#/alloc ns:ns-button))
235#&lt;NS-BUTTON &lt;NSButton: 0x13b7bec0&gt; (#x13B7BEC0)&gt;
236    </pre>
237
238    <p>As with the window, most of the interesting work is in
239    configuring the allocated button after it's allocated.</p>
240
241    <p>Instances of NSButton include pushbuttons with either text or
242    image labels (or both), checkboxes, and radio buttons. In order to
243    make a text pushbutton, we need to tell our button to use a
244    button-type of <code>NSMomentaryPushInButton</code>, an image
245    position of <code>NSNoImage</code>, and a border style
246    of <code>NSRoundedBezelStyle</code>. These style options are
247    represented by Cocoa constants.</p>
248   
249    <p>We also need to give the button a frame rectangle that defines
250    its size and position. We can once again
251    use <code>ns:with-ns-rect</code> to specify a temporary rectangle
252    for the purpose of initializing our button:</p>
253
254    <pre>
255(ns:with-ns-rect (frame 10 10 72 32)
256  (#/initWithFrame: my-button frame)
257  (#/setButtonType: my-button #$NSMomentaryPushInButton)
258  (#/setImagePosition: my-button #$NSNoImage)
259  (#/setBezelStyle: my-button #$NSRoundedBezelStyle))
260;Compiler warnings :
261;   Undeclared free variable MY-BUTTON (4 references), in an anonymous lambda form
262NIL
263    </pre>
264
265    <p>Now we just need to add the button to the window. This we do by
266    asking the window for its content view, and asking that view to
267    add the button as a subview:</p>
268
269    <pre>
270(#/addSubview: (#/contentView my-window) my-button)
271    </pre>
272
273    <p>The button appears in the window with the rather uninspired
274    title "Button". Clicking it highlights the button but, since we
275    didn't give it any action to perform, does nothing else.</p>
276
277    <p>We can give the button a more interesting title and, perhaps
278    more importantly, an action to perform, by passing a string and an
279    action to it. First, let's set the button title:</p>
280
281    <pre>
282(let ((label (%make-nsstring "Hello!")))
283  (#/setTitle: my-button label)
284  (#/release label))
285;Compiler warnings :
286;   Undeclared free variable MY-BUTTON, in an anonymous lambda form
287NIL
288    </pre>
289
290    <p>The button changes to display the text "Hello!". Notice that we
291    are careful to save a reference to the button text and release it
292    after changing the button title. The normal memory-management
293    policy in Cocoa is that if we allocate an object (like the
294    NSString "Hello!") we are responsible for releasing it. Unlike
295    Lisp, Cocoa does not automatically garbage-collect all allocated
296    objects by default.</p>
297
298    <p>Giving the button an action is slightly more
299    complicated. Clicking a button causes the button object to send a
300    message to a target object. We haven't given our button a message
301    to send, nor a target object to send it to, so it doesn't do
302    anything. In order to get it do perform some kind of action, we
303    need to give it a target object and a message to send. Then, when
304    we click the button, it will send the message we specify to the
305    target we provide. Naturally, the target object had better be able
306    to respond to the message, or else we'll just see a runtime
307    error.</p>
308
309    <p>Let's define a class that knows how to respond to a greeting
310    message, and then make an object of that class to serve as our
311    button's target.</p>
312
313    <p>We can define a subclass of <code>NSObject</code> to handle
314    our button's message:</p>
315
316    <pre>
317(defclass greeter (ns:ns-object)
318  ()
319  (:metaclass ns:+ns-object))
320#&lt;OBJC:OBJC-CLASS GREETER (#x13BAF810)&gt;
321    </pre>
322
323    <p>We'll need to define a method to execute in response to the
324    button's message. Action methods accept one argument (in addition
325    to the receiver): a sender. Normally Cocoa passes the button
326    object itself as the sender argument; the method can do anything
327    it likes (or nothing at all) with the sender.</p>
328
329    <p>Here's a method that displays an alert dialog:</p>
330
331    <pre>
332(objc:defmethod #/greet: ((self greeter) (sender :id))
333  (declare (ignore sender))
334  (let ((title (%make-nsstring "Hello!"))
335        (msg (%make-nsstring "Hello, World!"))
336        (default-button (%make-nsstring "Hi!"))
337        (alt-button (%make-nsstring "Hello!"))
338        (other-button (%make-nsstring "Go Away")))
339    (#_NSRunAlertPanel title msg default-button alt-button other-button)
340    (#/release title)
341    (#/release msg)
342    (#/release default-button)
343    (#/release other-button)))
344    </pre>
345
346    <p>Now we can create an instance of the Greeter class and use it
347    as the button's target:</p>
348
349    <pre>
350(setf my-greeter (#/init (#/alloc greeter)))
351#&lt;GREETER &lt;Greeter: 0x136c58e0&gt; (#x136C58E0)&gt;
352
353(#/setTarget: my-button my-greeter)
354NIL
355
356(#/setAction: my-button (@SELECTOR "greet:"))
357NIL
358    </pre>
359
360    <p>Now, if you click the button, an Alert panel appears.</p>
361
362    </div>
363
364  </body>
365</html>
366
Note: See TracBrowser for help on using the repository browser.