首页 文章

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

提问于
浏览
0

我在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

    代码行

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

    看起来很可疑,因为最后一行暗示 selfUIView 的某个子类 . 并且 viewWasTapped 选择器的目标应为 HomeViewController 类型 . 所以你可能需要将第二行的 target 更改为 homeVC .

相关问题