美文网首页UIKit
Masonry中查找View的公共公共父视图Superview;

Masonry中查找View的公共公共父视图Superview;

作者: kakukeme | 来源:发表于2016-12-28 18:16 被阅读524次
    View+MASAdditions.m
    查找两个view的公共父视图Superview;
    第一个view是自身self,第二个view是传进来的view;
    第一层遍历,找到第二个view的superView;
    第二层遍历,找到第一个view的superView,并判断和第二个view的superView是否相等,
    若相等赋值给closestCommonSuperview;
    如果closestCommonSuperview有值了,就跳出循环了;先跳出里面的while,在外面的while;
    - (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view {
        MAS_VIEW *closestCommonSuperview = nil;
    
        MAS_VIEW *secondViewSuperview = view;
        while (!closestCommonSuperview && secondViewSuperview) {
            MAS_VIEW *firstViewSuperview = self;
            while (!closestCommonSuperview && firstViewSuperview) {
                if (secondViewSuperview == firstViewSuperview) {
                    closestCommonSuperview = secondViewSuperview;
                }
                firstViewSuperview = firstViewSuperview.superview;
            }
            secondViewSuperview = secondViewSuperview.superview;
        }
        return closestCommonSuperview;
    }
    
    
    NSArray+MASAdditions.m
    查找数组中的子view的公共superView;
    首先遍历这个数组,只有UIView的class才继续遍历;
    前一个view(previousView)不为空,查找和previousView的公共父视图;
    循环依次进行下去;
    - (MAS_VIEW *)mas_commonSuperviewOfViews
    {
        MAS_VIEW *commonSuperview = nil;
        MAS_VIEW *previousView = nil;
        for (id object in self) {
            if ([object isKindOfClass:[MAS_VIEW class]]) {
                MAS_VIEW *view = (MAS_VIEW *)object;
                if (previousView) {
                    commonSuperview = [view mas_closestCommonSuperview:commonSuperview];
                } else {
                    commonSuperview = view;
                }
                previousView = view;
            }
        }
        NSAssert(commonSuperview, @"Can't constrain views that do not share a common superview. Make sure that all the views in this array have been added into the same view hierarchy.");
        return commonSuperview;
    }
    

    相关文章

      网友评论

        本文标题:Masonry中查找View的公共公共父视图Superview;

        本文链接:https://www.haomeiwen.com/subject/hcayvttx.html