Question

i'm tying to programmatically create a scrollView that will show a description.

my hierarchy is probably going to be like this:

->root View  
--->scroll View  
----->content View  
------->Label1  
------->Label2
------->Label3

here is an image that shows the structure of the app:

enter image description here

this is the code so far, i get what i want except that now i need to include all this inside a scrollView (that will scroll only vertically).
i tried many different things but i still don't get how to do it.

UIView *contentView = [UIView autolayoutView];
contentView.backgroundColor = [UIColor greenColor];
[self.view addSubview:contentView];
NSDictionary *views2 = NSDictionaryOfVariableBindings(contentView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[contentView]|" options:0 metrics:0 views:views2]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentView]" options:0 metrics:0 views:views2]];

UILabel *one = [UILabel autolayoutView];
UILabel *two = [UILabel autolayoutView];
UILabel *three = [UILabel autolayoutView];
for(UILabel *label in @[one,two,three]){
    label.backgroundColor = [UIColor redColor];
    label.text = @"fjeif\njeif\noesjf\nfjeif\njeif\noesjf\nfjeif\njeif\noesjf\nosfj";
    label.numberOfLines = 0;
    [contentView addSubview:label];
}
NSDictionary *views3 = NSDictionaryOfVariableBindings(one,two,three);
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[one]-|" options:0 metrics:0 views:views3]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[one(two)]-[two(three)]-[three]-|" options:NSLayoutFormatAlignAllLeft | NSLayoutFormatAlignAllCenterX metrics:0 views:views3]];

thanks, sorry if i didn't describe my problem well enough, i'm in a hurry. looking at the image should be enough to understand though.

Was it helpful?

Solution

I had the same problem though I set all constraints from XIB. You can do like this.

Add leading edge, trailing edge, top space and bottom space constraints to labels with respect to container view. Then you can add these same constraints to container view with respect to scrollView. Do the same exercise for scrollView. You just need to add one more constraint (Horizontally center in container view constraint)to container view. Hope this will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top