我也有同样的问题,我正在创建一个教程视图,我想在其中将多个 UIViews 添加到滚动视图中。当我试图从 xib 获取框架时,它总是给出 320,因此页面的偏移量是错误的,我的视图在 iPhone6 和 6plus 中看起来很糟糕。
然后我使用纯自动布局方法,即不使用框架,而是通过 VFL 添加约束,以便子视图完全适合父视图。下面是我从 Xib 创建大约 20 个 UIView 并正确添加到滚动视图的代码快照
完整代码在这里ScrollViewAutolayout
Method to layout the childviews in the scrollview.
@param nil
@result layout the child views
*/
-(void)layoutViews
{
NSMutableString *horizontalString = [NSMutableString string];
// Keep the start of the horizontal constraint
[horizontalString appendString:@"H:|"];
for (int i=0; i<viewsArray.count; i++) {
// Here I am providing the index of the array as the view name key in the dictionary
[viewsDict setObject:viewsArray[i] forKey:[NSString stringWithFormat:@"v%d",i]];
// Since we are having only one view vertically, then we need to add the constraint now itself. Since we need to have fullscreen, we are giving height equal to the superview.
NSString *verticalString = [NSString stringWithFormat:@"V:|[%@(==parent)]|", [NSString stringWithFormat:@"v%d",i]];
// add the constraint
[contentScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:verticalString options:0 metrics:nil views:viewsDict]];
// Since we need to horizontally arrange, we construct a string, with all the views in array looped and here also we have fullwidth of superview.
[horizontalString appendString:[NSString stringWithFormat:@"[%@(==parent)]", [NSString stringWithFormat:@"v%d",i]]];
}
// Close the string with the parent
[horizontalString appendString:@"|"];
// apply the constraint
[contentScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:horizontalString options:0 metrics:nil views:viewsDict]];
}