3

I'm trying to add one subview (view from an NSViewController) for every element in a dictionary to a NSScrollView to get kind of a tableview, but with much more flexibility over the cells.

Is it possible to place (programmatically) e.g. 100 subviews underneath each other so that you have to scroll down the NSScrollView to get to the last element?

BenMorel
  • 34,448
  • 50
  • 182
  • 322

2 Answers2

4

The short answer is yes. I have done this before, and I assure you that it will work. Let me also assure you that it is not quite as simple as it looks ;)

The way to do this is to maintain one content view, in which you add all of your custom rows as subviews programmatically. Note that you will either have to resize the contentView before adding all of the rows, or you will have to turn off autoresizing for the row views. Set the documentView of your scrollView to this custom contentView, and you should be good to go.

e.James
  • 116,942
  • 41
  • 177
  • 214
  • 1
    "…either…resize the contentView before…or…turn off autoresizing…" Can you elaborate? Why do you have to do this? – Chris Page Oct 04 '11 at 04:06
  • @Chris Page: if you add a bunch of subviews to a parent view, and then resize that parent view, the subviews will resize automatically according to the flags set in their autoresizing masks. For example, consider row views that are set to autoresize, and are originally 100 pixels tall. When you add 10 of these to a contentView that is only 500 pixels tall, and then resize the contentView to be 1000 pixels tall, each row will resize to be 200 pixels tall. – e.James Oct 04 '11 at 13:56
1

Yes, simply initialize the views programmatically using (i.e.)

NSView *subView = [[NSView alloc] initWithFrame:CGRectMake(10,10,100,100)];

then add to the main using addSubview: method of the main view.
Remember to manually release the subview when you've done with it (that means, when you have added it to the main view).

As example you can do something like

int height x = 10, y = 10, width = 100, height = 100;

for(int i = 0;i<100;i++) {
    NSView *subView = [[NSView alloc] initWithFrame:CGRectMake(x,y + height*i,width,height)];
    [scrollView addSubview:subView];
    [subView release];
}
Manlio
  • 10,768
  • 9
  • 50
  • 79