如何在ViewWIllAppear上重新布局视图?



ViewWillAppear里面有以下代码:

CGFloat typeViewHeight = self.scrollview.frame.size.height;
CGFloat typeViewWidth = 120;
for (UIView *view in [self.scrollview subviews]) {
if([view isKindOfClass:[TypeSelectionItemView class]]) {
[view removeFromSuperview];
}
}
for (int i = 0; i < typeArray.count; ++i) {
TypeSelectionItemView *typeView = nil;
CGRect frame = CGRectMake(typeViewWidth * i, 0, typeViewWidth, typeViewHeight);
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"TypeSelectionItemView" owner:self options:nil];
for(id currentObject in topLevelObjects){
if([currentObject isKindOfClass:[TypeSelectionItemView class]]){
typeView = (TypeSelectionItemView *) currentObject;
break;
}
}
[self.typeScrollView setContentSize:CGSizeMake(typeViewWidth * (i + 1), typeViewHeight)];
[self.typeScrollView addSubview:typeView];
}

当我在应用程序中看到子视图的位置和大小不正确时,但是,如果我将其放置在ViewDidAppear内,子视图的位置和大小是正确的,但是视图为时已晚,无法向用户显示。

有什么方法可以通过将这些代码放在ViewWillAppear中来解决它?

我已经在ViewWillAppear中尝试了这些代码,但根本不起作用:

[self.typeScrollView setNeedsUpdateConstraints];
[self.typeScrollView updateConstraintsIfNeeded];
[self.typeScrollView setNeedsLayout];
[self.typeScrollView layoutSubviews];
[self.typeScrollView layoutIfNeeded];

将代码移动到ViewWillAppearViewWillLayoutSubview
如果您需要在ViewDidAppear之前获取任何视图的真实帧/大小.
只需将这两行放在上面:

// Force scrollView to layout subview
scrollView.setNeedsLayout()
scrollView.layoutIfNeeded()
// ...

希望有用!

最新更新