When you are using AutoLayout, you should avoid setting the contentSize of UIScrollView and instead depend on the subview's height and bottom constraint to let the UIScrollView calculate it internally.
Second, you are using an unwanted UIView to render your subviews.You don't need ContentView to host your subviews. Directly add those to mainScroll
view.
Use this code to layout subviews vertically in your scroll view. Here i have taken some assumptions such as view.width = mainScroll.width
and view.width = view.height
and view is having a padding of 5px to each boundry. You can make changes as you like.
First, create an instance variable in your class as:
UIView *lastView;
NSInteger arrayCount;
Then replace your setUI
code with this
-(void)setUI
{
lastView = nil;
arrayCount = [array count];
for(NSInteger index =0; index < arrayCount; index++)
{
UIView *view = [self GetAlertView:i];
[self.mainScroll addSubview:view];
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.mainScroll addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|" options:0 metrics:nil views:@{@"view":view}]];
//--> If View is first then pin the top to main ScrollView otherwise to the last View.
if(lastView == nil && index == 0) {
[self.mainScroll addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[view]" options:0 metrics:nil views:@{@"view":view}]];
}
else {
[self.mainScroll addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lastView]-5-[view]" options:0 metrics:nil views:@{@"lastView":lastView, @"view":view}]];
}
[self.mainScroll addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.mainScroll attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
[self.mainScroll addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
//--> If View is last then pin the bottom to mainScrollView bottom.
if(index == arrayCount-1) {
[self.mainScroll addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view]-5-|" options:0 metrics:nil views:@{@"view":view}]];
}
//--> Assign the current View as last view to keep the reference for next View.
lastView = view;
}
}