查找两个子视图的共同父视图

343 阅读1分钟

extension ViewController {
    func findCommonSuperView(viewA: UIView,
                             viewB: UIView) -> [UIView] {
        
        var temp = viewA
        
        var array1 = [UIView]()
        while (temp.superview != nil) {
            array1.append(temp.superview!)
            temp = temp.superview!
        }
        
        temp = viewB
        var array2 = [UIView]()
        while (temp.superview != nil) {
            array2.append(temp.superview!)
            temp = temp.superview!
        }
        
        var i = 0
        var result_array = [UIView]()
        while i < min(array1.count, array2.count) {
            let sup1 = array1[array1.count - 1 - i]
            let sup2 = array2[array2.count - 1 - i]
            if sup1 == sup2 {
                result_array.append(sup1)
                i += 1
            } else {
                break
            }
        }
        
        return result_array
    }
}