iphone - UIView的setNeedsLayout、layoutIfNeeded和layoutSubviews之间有什么关系?

标签 iphone xcode uiview

任何人都可以对UIView的 setNeedsLayoutlayoutIfNeededlayoutSubviews方法之间的关系给出明确的解释吗?以及一个使用所有三个的示例实现。谢谢。

让我感到困惑的是,如果我向自定义 View 发送 setNeedsLayout 消息,那么它在此方法之后调用的下一个内容是 layoutSubviews,直接跳过 布局IfNeeded。从文档中,我期望流程为 setNeedsLayout > 导致 layoutIfNeeded 被调用 > 导致 layoutSubviews 被调用。

最佳答案

我仍在尝试自己解决这个问题,因此请对此持怀疑态度,如果其中包含错误,请原谅我。

setNeedsLayout 是一个简单的方法:它只是在 UIView 中的某个位置设置一个标志,将其标记为需要布局。这将强制在下一次重绘发生之前在 View 上调用 layoutSubviews 。请注意,在许多情况下,您不需要显式调用此函数,因为有 autoresizesSubviews 属性。如果已设置(默认情况下),则对 View 框架的任何更改都将导致 View 布置其 subview 。

layoutSubviews 是您执行所有有趣操作的方法。如果您愿意的话,它相当于布局的 drawRect 。一个简单的例子可能是:

-(void)layoutSubviews {
    // Child's frame is always equal to our bounds inset by 8px
    self.subview1.frame = CGRectInset(self.bounds, 8.0, 8.0);
    // It seems likely that this is incorrect:
    // [self.subview1 layoutSubviews];
    // ... and this is correct:
    [self.subview1 setNeedsLayout];
    // but I don't claim to know definitively.
}

AFAIK layoutIfNeeded 通常并不意味着在子类中被覆盖。当您想要立即布置 View 时,您应该调用该方法。立即。 Apple 的实现可能如下所示:

-(void)layoutIfNeeded {
    if (self._needsLayout) {
        UIView *sv = self.superview;
        if (sv._needsLayout) {
            [sv layoutIfNeeded];
        } else {
            [self layoutSubviews];
        }
    }
}

您可以在 View 上调用 layoutIfNeeded 来强制立即布局该 View (及其必要的父 View )。

关于iphone - UIView的setNeedsLayout、layoutIfNeeded和layoutSubviews之间有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2807137/

相关文章:

ios - 将经历默认参数提升的对象传递给 'va_start'

xcode - 没有错误显示时调试 GDB 中断

ios - 无法在 UIView 前面绘制 SKLabelNode

ios - 收集 View IOS 中的 UILABEL 换行符

ios - 尝试在 iOS 的 for 循环内动态创建和填充两个 View

ios - UIImage 不会在 UIView 运行转换上显示

iphone - 在沙盒环境中测试时出现应用内购买错误

iphone - 非 UIView 动画 : animations not playing sometimes, UIView 动画:工作正常

iphone - 使 UILabel 可触摸

xcode - 无法向引导服务器注册