Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically added subviews in a UIScrollView not appearing

Tags:

ios

iphone

I'm having a lot of trouble dynamically adding subviews to a UIScrollView. The scroll view works fine with content created in a NIB but since the subviews to be displayed depend on data in my application (a mixture of images, labels, radio buttons, etc.) I need to be able to create and display them dynamically.

According to everything I've read it seems pretty straightforward on various sites and in the Apple documentation. In the view controller's viewDidLoad, I've added the following code,

UILabel *testLabel = [[UILabel alloc] init];
[testLabel setFrame:CGRectMake(50, 50, 100, 40)];
[testLabel setText:@"My Test label"];
[scrollView addSubview:testLabel];

[testLabel release];

The label will not appear in the scroll view at all but if I add the testLabel to self.view, then it appears (but not in the scrolling content obviously). I even tried adding the code to viewDidAppear in case I misunderstood the order of events with no luck.

When I checked the debugger, I noticed that the address of the scroll view is 0x0 which I assume means its null for some reason which would explain why its not working. I was under the assumption that if I connected this scrollView pointer to the actual scroll view in IB, it would be automatically assigned the correct address. Is this incorrect? If this is the case, how do I go about getting the address of the view?

-- UPDATE --
Thanks for all the feedback. I checked everything as everybody suggested and it was certainly all correct. I didn't need to set the size of the content as I had some other dummy labels (for testing that the scrolling was working) in the NIB. But I'll remember that for later on :-)

Interestingly, though, after checking the code again and not making any changes, I ran it again and it just worked!! Not sure why but I'll post the reason if I ever figure it out...

like image 448
richard Avatar asked Oct 05 '11 09:10

richard


1 Answers

When you use scrollView you need to set the content size by doing:

scrollView.contentSize = CGSizeMake(@width,@height);

In this case the size should be bigger the 50,50 if you wanna see the label

Hope it helped

like image 62
Or Ron Avatar answered Sep 26 '22 15:09

Or Ron