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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With