【问题标题】:Swift recognize tableView cell tap areaSwift识别tableView单元格点击区域
【发布时间】:2021-11-07 17:28:21
【问题描述】:

如何以 porgrmatically 检测 tableView 单元格的特定区域?

例如,如果用户点击 tableView 单元格的左半部分,则会调用 didSelectRowAt 并识别单元格的左半部分。

伪:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    print("Entire cell tapped")

    if(left side of cell pressed){
      //cell.width /2
      print("left side half of cell pressed")
   }
}

【问题讨论】:

    标签: ios swift uitableview tableview


    【解决方案1】:

    根据this线程,添加手势识别器可能会与TableView交互冲突。

    因此,要实现您的要求,您必须将手势识别器添加到 UITableViewCellcontentView 并获取手势的点击位置。为此,

    1. 首先,定义UITapGestureRecognizerUITableViewCell 类中的操作。参考以下代码
        lazy var tap = UITapGestureRecognizer(target: self, action: #selector(didTapScreen))
    .
    .
    .
        // Gesture action
        @objc func didTapScreen(touch: UITapGestureRecognizer) {
            let xLoc = touch.location(in: self.contentView).x // Getting the location of tap
            if xLoc > contentView.bounds.width/2 {
                // RIGHT
            } else {
                // LEFT
            }
        }
    
    1. 在自定义单元格的init()方法中添加如下内容
        override init(frame: CGRect) {
            super.init(frame: frame)
            tap.numberOfTapsRequired = 1
            contentView.addGestureRecognizer(tap)
            // Other setups
        }
    

    我在UICollectionViewCell 中尝试了代码并得到了以下输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      相关资源
      最近更新 更多