12

似乎在视图上viewDidLayoutSubviews调用之后立即layoutSubviews调用,在该视图的子视图上调用之前layoutSubviews。有什么方法可以知道何时layoutSubviews调用了视图及其所有也需要更新其布局的子视图?

4

2 回答 2

4

You shouldn't have to know if the subviews of a subview have updated their layout: That sounds like too tight coupling. Also, each subview might handle the arrangement of their respective subviews differently and might not (need to) call layoutSubviews for its subviews at all. You should only ever have to know about your direct subviews. You should treat them more or less as black boxes and not care whether they have subviews of their own or not.

于 2013-12-24T19:20:34.190 回答
0

如前所述@Johannes Fahrenkrug,您应该“将它们视为黑匣子”。但根据我的理解,那是因为可可就是不能承诺。

如果您确实需要在所有子视图完成布局工作时收到通知,这里有一个核心示例可以解决您的问题。我也不保证它会在任何情况下都有效。

- (void) layoutSubviewsIsDone{
    // Your code here for layoutSubviews is done
}

// Prepare two parameters ahead
int timesOfLayoutSubviews = 0;
BOOL isLayingOutSubviews = NO;

// Override the layoutSubviews function
- (void) layoutSubviews{
     isLayingOutSubviews = YES;  // It's unsafe here!
     // you may move it to appropriate place according to your real scenario

     // Don't forget to inform super
     [super layoutSubviews];
}

// Override the setFrame function to monitor actions of layoutSubviews
- (void) setFrame:(CGRect)frame{
     if(isLayingOutSubviews){
        if(frame.size.width == self.frame.size.width
        && frame.size.height == self.frame.size.height
        && frame.origin.x == self.frame.origin.x
        && frame.origin.y == self.frame.origin.y
        && timesOfLayoutSubviews ==self.subviews.count){
            isLayingOutSubviews = NO;
            timesOfLayoutSubviews = 0;
            [self layoutSubviewsIsDone];  // Detected job done, call your function
    }else{
        timesOfLayoutSubviews++;
    }
}
于 2014-08-13T14:35:50.330 回答