[Swift] How does UICollectionView monitor the blank area of the view being clicked

Empty space in UICollectionView refers to the area that does not contain any cells.

To listen to the blank area being clicked, you can add a UITapGestureRecognizer to UICollectionView, and handle the event that the blank area is clicked in the callback method of the gesture recognizer.

// 创建 UITapGestureRecognizer 对象
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))

// 将 UITapGestureRecognizer 添加到 UICollectionView 上
collectionView.addGestureRecognizer(tapGesture)

// 处理空白区域被点击的事件
@objc func handleTap(_ gesture: UITapGestureRecognizer) {
    // 获取手势在 UICollectionView 上的位置
    let location = gesture.location(in: collectionView)
    
    // 检查是否点击了空白区域
    if let indexPath = collectionView.indexPathForItem(at: location) {
        // 点击了cell
    } else {
        print("空白区域被点击了")
    }
}

Guess you like

Origin blog.csdn.net/u012881779/article/details/130357442