要实现在 UICollectionViewCell 上点击 UITextView 并执行 Cell 的 didSelect 代理方法,可以通过以下步骤来实现:

  1. 在 UICollectionViewCell 中添加一个 UITextView,并设置它的 'isEditable' 属性为 false,这样就可以禁止编辑。
  2. 在 UICollectionViewCell 中添加一个 UITapGestureRecognizer 来检测 UITextView 的点击事件。
  3. 在 UITapGestureRecognizer 的回调方法中,调用 Cell 的 didSelect 代理方法。

以下是一个示例代码:

class MyCollectionViewCell: UICollectionViewCell {
    weak var delegate: MyCollectionViewCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let textView = UITextView(frame: contentView.bounds)
        textView.isEditable = false
        contentView.addSubview(textView)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(textViewTapped))
        textView.addGestureRecognizer(tapGesture)
    }
    
    @objc func textViewTapped() {
        delegate?.collectionViewCellDidSelect(self)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

protocol MyCollectionViewCellDelegate: AnyObject {
    func collectionViewCellDidSelect(_ cell: MyCollectionViewCell)
}

class MyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, MyCollectionViewCellDelegate {
    // ...
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellIdentifier", for: indexPath) as! MyCollectionViewCell
        cell.delegate = self
        // Configure the cell
        return cell
    }
    
    func collectionViewCellDidSelect(_ cell: MyCollectionViewCell) {
        // Handle cell selection here
    }
}

通过这种方式,你可以在 UICollectionViewCell 上点击 UITextView,并执行 Cell 的 didSelect 代理方法。

Swift: 点击 UICollectionViewCell 内不可编辑的 UITextView,触发 Cell 的 didSelect 代理方法

原文地址: https://www.cveoy.top/t/topic/fC01 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录