Add lots of views to NSScrollView

2019-05-20 17:28发布

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???

Thanks in advanced, Grolior

2条回答
戒情不戒烟
2楼-- · 2019-05-20 17:53

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];
}
查看更多
一夜七次
3楼-- · 2019-05-20 18:09

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.

查看更多
登录 后发表回答