美文网首页
iOS开发在子视图中获取父控制器、父视图

iOS开发在子视图中获取父控制器、父视图

作者: lczalh | 来源:发表于2018-10-16 17:09 被阅读407次

oc

通过当前视图获取父视图的控制器
- (UIViewController *)LCZGetSuperViewController:(UIView *)view
{
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[HomePageViewController class]]) {
            return (HomePageViewController *)nextResponder;
        }
    }
    return nil;
}

swift

/// 通过当前视图获取父视图的控制器
///
/// - Parameters:
///   - currentView: 当前视图
///   - viewController: 需要获取到的控制器
/// - Returns: 返回控制器
func LCZGetSuperViewController<T: UIViewController>(currentView:UIView, viewController: T.Type) -> T? {
        var view: UIView = currentView.superview!
        
        while view.next!.isKind(of: T.self) != true {
            guard view.superview != nil else {
                return nil
            }
            view = view.superview!
        }
        return view.next as? T
}

/// 获取当前视图中的目标父视图
///
/// - Parameters:
///   - currentView: 当前视图
///   - superView: 目标父视图
/// - Returns: 返回父视图
public func LCZGetSuperView<T: UIView>(currentView: UIView, superView: T.Type) -> T? {
    var view: UIView = currentView.superview!
    
    while view.isKind(of: T.self) != true {
        guard view.superview != nil else {
            return nil
        }
        view = view.superview!
    }
    return view as? T
}

相关文章

网友评论

      本文标题:iOS开发在子视图中获取父控制器、父视图

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