Search code examples
cocoaboxlayout

BoxLayout in Cocoa


Originally, I wanted to ask how to create user interfaces with cocoa programmatically, i.e. without using interface builder. But it seems that someone else has already asked this question and the answers didn't help me.

So I'll ask a different question, that I hope will indirectly help me answer the previous question. Here it is:

(QUESTION_START)

How do I create an Objective C class that is equivalent in functionality with the BoxLayout class in Java? (Just click the link, the image on that page says everything you need to know about BoxLayout.)

(QUESTION_END)

Any help in the right direction will be appreciated!

There are a few sub tasks that are connected with the question, e.g.

"How do I ask a user interface element (e.g. a button) how large it wants to be" (before it has been drawn to the screen). To draw it on the screen you have to already know its size, don't you? Obviously, the interface builder application has figured out a way to do this.

I know that many Cocoa developers think it's a stupid idea to even try what I want to do. Let me tell you: I know the reasoning behind that opinion. Right now, laying out controls without interface builder sucks, because there is nothing that comes even close to a layout manager in cocoa. But if you think my question is stupid, please DONT answer. The whole internet is full of explanations why you would never want to create UIs with code in cocoa.

Thanks!


Solution

  • Answering your first question is kind of difficult and fairly involved, so I'm going to dive into your subquestion first:

    How do I ask a user interface element (e.g. a button) how large it wants to be?

    When you create a UI element, you tell it how big it should be (as well as where it should be) via its initWithFrame: constructor; or you can set its frame later via its setFrame: method. It will then draw itself into that space. You can get an element's frame via its frame method.

    With that in mind, a BoxLayout class would, hypothetically, be a controller of some sort in which you could add UI elements, and then the BoxLayout controller would arrange them in a grid (or whatever) on an NSView of some sort.

    I know you weren't looking for answers that questions motives, but given the complexity of a BoxLayout class vs. laying out the interface in IB, it seems relevant to ask why you want to do this.