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

时间:2018-06-05 02:51:05

标签: ios objective-c uiscrollview

我在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];

1 个答案:

答案 0 :(得分:0)

将您的代码移至ViewWillAppearViewWillLayoutSubview
如果您需要在ViewDidAppear之前获得任何视图的实际帧/大小。
只需将这两行放在上面:

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

希望它有用!