如何检查子视图控制器是否存在

时间:2019-01-28 12:48:46

标签: ios swift uiviewcontroller

我正在样式菜单中实现幻灯片。

菜单被添加为节目中的子视图控制器,然后动画化为视图。关闭后,我便从视图中将其删除。

我想引入一个UIPanGestureRecognizer,以便用户可以将其滑动到视图中,但是添加视图的逻辑仅在按下open时触发。

我想避免在每个手势上多次添加它,所以我正在考虑检查它是否存在,如果不添加它,然后进行动画处理。

lazy var menuController = MenuController()

private var menuWidth: CGFloat = 300
private let keyWindow = UIApplication.shared.keyWindow

override func viewDidLoad() {
    super.viewDidLoad()

    setupNavigationItems()
    setupTableView()

    menuController.view.frame = CGRect(x: -menuWidth, y: 0, width: menuWidth, height: view.frame.height)

    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
    view.addGestureRecognizer(panGesture)

}

@objc func handlePan(gesture: UIPanGestureRecognizer) {


    let translation = gesture.translation(in: view)
    let transform = CGAffineTransform(translationX: translation.x, y: 0)
    menuController.view.transform = transform
    navigationController?.view.transform = transform

}

@objc func handleOpen() {
    keyWindow?.addSubview(menuController.view)
    animateMenuController(transform: CGAffineTransform(translationX: self.menuWidth, y: 0)) { }

    addChild(menuController)

}

@objc func handleHide() {
    animateMenuController(transform: .identity) { [weak self] in
        self?.menuController.view.removeFromSuperview()
        self?.menuController.removeFromParent()
    }
}

我希望做这样的事情

    @objc func handlePan(gesture: UIPanGestureRecognizer) {

        if view.subviews.contains(MenuController) {
            print("yes")
        }


        let translation = gesture.translation(in: view)
        let transform = CGAffineTransform(translationX: translation.x, y: 0)
        menuController.view.transform = transform
        navigationController?.view.transform = transform

    }

但这是不正确的。

2 个答案:

答案 0 :(得分:2)

您可以根据班级名称检查classForCoder

if children.first(where: { String(describing: $0.classForCoder) == "MenuController" }) != nil {
    print("we have one")
}

这确实引入了“魔术字符串”,但是仅仅更改类名会破坏这种逻辑。

答案 1 :(得分:1)

您可以尝试使用vc的childrens属性

if !children.isEmpty { // this assumes 1 vc tell if you have more
   print("YES")  
}

if let _ = children.first(where:{ $0 is menuController})  {  // this assumes 1 vc tell if you have more
   print("YES")  
}

您可能还需要将其添加到

 view.addSubview(menuController.view)

不要keyWindow