UITapGestureRecognizer点击崩溃:UIView收到未识别selector问题求助
问题解决:UITableView表头图片点击手势导致崩溃
崩溃原因
你把手势的target设成了表头的UIView实例,但showHint方法是定义在当前视图控制器里的。当手势触发时,系统会尝试给这个UIView发送showHint:消息,而UIView本身并没有这个方法,所以抛出了unrecognized selector异常。
修复步骤
- 修改手势的target为
self(当前视图控制器),因为showHint是这个类的方法:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { // 把target从view改成self let tap = UITapGestureRecognizer(target: self, action: #selector(showHint)) hintImageView.isUserInteractionEnabled = true hintImageView.addGestureRecognizer(tap) } @objc func showHint(_ sender: UITapGestureRecognizer) { print("hi") // 这里添加跳转页面的逻辑 }
- 额外检查:确保
hintImageView确实是当前表头视图中的那个UIImageView,避免出现引用错误或者nil的情况。如果是自定义表头视图,建议先将view强转为你的自定义表头类,再获取里面的图片视图,比如:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { guard let headerView = view as? CustomHeaderView else { return } let hintImageView = headerView.hintImageView let tap = UITapGestureRecognizer(target: self, action: #selector(showHint)) hintImageView.isUserInteractionEnabled = true hintImageView.addGestureRecognizer(tap) }
内容的提问来源于stack exchange,提问作者AMR AL-KHAYAT
相关产品推荐
相关产品推荐

