尝试在自定义UIView子类上使用tap识别器时出现NSUncaughtException

时间:2017-03-13 00:55:35

标签: ios uiview swift3 subclass uitapgesturerecognizer

我的viewController&上有几个UIViews。我想点击它们带我到不同的视图控制器。我有自定义UIView外观的自定义UIView子类,因为我无法从子类导航,所以创建了一个委托协议,允许我从视图控制器导航

协议:

protocol TapDelegate {
  func viewWasTapped()
}

在视图控制器上我已经符合这个协议,创建了一个自定义子视图的实例(常量是图标),最后我创建了一个导航到各种视图控制器的函数:

func viewWasTapped() {
    print("icon was tapped")    

    if icons.tag == 0 {

        let food_Tabs_VC = self.storyBoard.instantiateViewController(withIdentifier: String(describing: FoodTabsViewController.self)) as! FoodTabsViewController
        self.navigationController?.pushViewController(food_Tabs_VC, animated: true)

    } else if icons.tag == 1 {

        let movesVC = self.storyBoard.instantiateViewController(withIdentifier: String(describing: MovesViewController.self)) as! MovesViewController
        self.navigationController?.pushViewController(movesVC, animated: true)
    } else if icons.tag == 2 {

        let msgLogVC = self.storyBoard.instantiateViewController(withIdentifier: String(describing: MsgLogViewController.self)) as! MsgLogViewController
        self.navigationController?.pushViewController(msgLogVC, animated: true)

    } else {

        let myWorldVC = self.storyBoard.instantiateViewController(withIdentifier: String(describing: MyWorldViewController.self)) as! MyWorldViewController
        self.navigationController?.pushViewController(myWorldVC, animated: true)
    }

}

然而,当我尝试在我的自定义UIView子类中使用点击手势时,当我点击UIView时,我得到未捕获异常的错误,这里是点击手势代码:

let homeVC = HomeViewController()

let gesture = UITapGestureRecognizer(target: self, action:#selector(homeVC.viewWasTapped))
self.addGestureRecognizer(gesture)

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

代码行

let homeVC = HomeViewController()

let gesture = UITapGestureRecognizer(target: self, action:#selector(homeVC.viewWasTapped))
self.addGestureRecognizer(gesture)

对我来说很可疑,因为最后一行暗示selfUIView的某个子类。 viewWasTapped选择器的目标应为HomeViewController类型。因此,您可能需要将第二行中的target更改为homeVC