Detect Tap on UIImageView within UITableViewCell

前端 未结 6 1575
无人及你
无人及你 2021-02-20 11:40

I have a custom complex UITableViewCell where there are many views. I have an UIImageView within it which is visible for a specific condition. When it\'s visible ,

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 12:30

    Another one, with the indexPath, if it's ok for you to handle the tap in DataSource:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId)! as! ...ListCell
        ...
        cell.theImage.isUserInteractionEnabled = true
        let onTap = UITapGestureRecognizer(target: self, action: #selector(onTapImage))
        onTap.numberOfTouchesRequired = 1
        onTap.numberOfTapsRequired = 1
        cell.theImage.addGestureRecognizer(onTap)
        ...
        return cell
    }
    
    func onTapImage(_ sender: UITapGestureRecognizer) {
        var cell: ...ListCell?
        var tableView: UITableView?
        var view = sender.view
        while view != nil {
            if view is ...ListCell {
                cell = view as? ...ListCell
            }
            if view is UITableView {
                tableView = view as? UITableView
            }
            view = view?.superview
        }
    
        if let indexPath = (cell != nil) ? tableView?.indexPath(for: cell!) : nil {
            // this is it
        }
    }
    

    You may want to make the code shorter if you have only one tableView.

提交回复
热议问题