【发布时间】:2018-11-14 10:09:05
【问题描述】:
我在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];
【问题讨论】:
-
将您的代码放在
- (void)viewWillLayoutSubviews方法中,而不是ViewWillAppear -
然后会被调用多次。仅在
viewWillLayoutSubviews内部调用一次无济于事 -
@Rendy 将您的代码移动到
viewWillLayoutSubviews并使用布尔值进行检查并使其仅调用一次。 -
试试@trungduc 的建议。它应该工作
-
是的,它已经可以工作了。。早些时候还有另一个问题,所以设法解决了它们。谢谢!
标签: ios objective-c uiscrollview