【问题标题】:How to relayout views on ViewWIllAppear?如何重新布局 ViewWIllAppear 上的视图?
【发布时间】: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


【解决方案1】:

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

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

希望有用!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多