1. 程式人生 > >Masonry 部分原始碼分析

Masonry 部分原始碼分析

 尋找最近的公共父檢視

- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view {
    MAS_VIEW *closestCommonSuperview = nil;

    MAS_VIEW *secondViewSuperview = view;

// 先是用view和self及self的父檢視們挨個的比較,然後是用view的父檢視們和self及self的父檢視們挨個的比較
// 這個while結束的條件是:1、內部while找到了closestCommonSuperview;2、找遍了傳進來的view的所有父檢視後secondViewSuperview變成了nil
    while (!closestCommonSuperview && secondViewSuperview) {
        MAS_VIEW *firstViewSuperview = self;

// 這個while結束的條件是:1、self或者self的父檢視們中有一個 和傳進來的view是同一個檢視;2、找遍了所有的父檢視後firstViewSuperview變成了nil
        while (!closestCommonSuperview && firstViewSuperview) {
            if (secondViewSuperview == firstViewSuperview) {
                closestCommonSuperview = secondViewSuperview;
            }
            firstViewSuperview = firstViewSuperview.superview;
        }
        secondViewSuperview = secondViewSuperview.superview;
    }
    return closestCommonSuperview;
}