You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UITapGestureRecognizer点击崩溃:UIView收到未识别selector问题求助

问题解决:UITableView表头图片点击手势导致崩溃

崩溃原因

你把手势的target设成了表头的UIView实例,但showHint方法是定义在当前视图控制器里的。当手势触发时,系统会尝试给这个UIView发送showHint:消息,而UIView本身并没有这个方法,所以抛出了unrecognized selector异常。

修复步骤

  1. 修改手势的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")
    // 这里添加跳转页面的逻辑
}
  1. 额外检查:确保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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:26:28