Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I draw a grid of squares in Cocoa?
    text
    copied!<p>I'm working on a visual <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">Conway's Game of Life</a> program for Cocoa. The main view, of course, is basically a grid of square tiles that change color between black and white as the algorithm progresses, but I'm having trouble figuring out the best way to draw and manage this grid of squares.</p> <p>My initial idea was to have each tile be a subclass of NSView. Drawing would be pretty simple: just fill it in black if it's alive, white if it's dead. But I'm not sure how to lay it out in a window; laying it out in Interface Builder as individual NSViews (and setting up the IB outlets for each one) seems tedious. I could position them programmatically, but that seems tedious, too (especially since I'd like to have a bit of space between each tile).</p> <p>I remembered that NSMatrix was expressly designed to work with an array (or grid) of interface objects, so I figured I could just create an NSMatrix of my NSView subclass. The problem is, it seems you can only create an NSMatrix of NSControls. My custom tile view isn't really a <em>control</em> per se, since it won't need to accept mouse tracking events or the like, but I figured I could fake it and use it just for drawing (and just ignore any events).</p> <p>Of course, if you're using a whole bunch of the same type of NSControl, it's best to use NSCell to do the drawing, but NSCell seems to be more geared towards drawing text- or image-based controls; I don't see a simple way to just draw a rect black or white.</p> <p>I'm leaning towards abusing an NSControl subclass to do the drawing, and skipping out on associating an NSCell with that, but I wondered if there's a better way or something I haven't thought of yet.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload