首页 > 解决方案 > UICollectionViewCell 中归档的可编辑文本阻止调用 didSelectItemAt

问题描述

UICollectionViewCell有一个文本字段,当我单击单元格时,它可以让我编辑文本字段,但没有调用didSelectItemAt函数。UICollectionViewDelegate我该如何克服呢?

class LetterCell: UICollectionViewCell {
    @IBOutlet weak var singleLetterTextField: UITextField!

    @IBAction func textDidChange(_ sender: Any) {
        if ((singleLetterTextField.text?.count)! > 1) {
            singleLetterTextField.text = String((singleLetterTextField.text?.last)!)
        }
    }
}

这是collectionView函数

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LetterCell", for: indexPath) as! LetterCell
    cell.singleLetterTextField.text = data[row][column]

    increaseRowColumn()

    return cell
}

而且我已经将委托和数据源设置为控制器。

标签: iosswiftuicollectionviewuicollectionviewcell

解决方案


  1. 考虑到您需要可编辑文本字段。
  2. didSelect如果在文本字段之外触摸单元格,则将起作用。
  3. 这并非不可能,因此如果您想在didSelect编辑的同时进行识别,则需要在 textField 中进行计算didBeginEditing。一个基本的技巧是将索引路径的值设置为标签或您的其他属性textfield,在cellForItemAt(例如检查)。您也可以创建自定义文本字段。

这是您的更新cellForItemAt

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LetterCell", for: indexPath) as! LetterCell
    cell.singleLetterTextField.text = data[row][column]

    cell.singleLetterTextField.tag = indexPath.row//then you can use this tag to form indexPath and with that you can retrieve cell (if it's still visible)

    increaseRowColumn()

    return cell
}

推荐阅读