在 UICollectionView 中点击按钮时输入 UITextField



我需要您的帮助来了解如何在点击按钮时与UITextField进行交互。

这是我ViewController中的代码:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
    cell.addBookTapped.addTarget(self,action: #selector(buttonTapped(_:)),for: .touchUpInside)
    cell.configureCell(with: books[indexPath.row], indexCell: indexPath.row )
    return cell
}
func buttonTapped(_ sender: UIButton)
{
    let tag = sender.tag
    //Do Stuff
}

在我的MyCollectionViewCell中,我配置了所有按钮和textView,并在按钮中添加标签:

@IBOutlet weak var myTextFielThatIWantToFieldWhenButtonTapped: UITextField!

在我func buttonTapped里面的ViewController我无法到达myTextFielThatIWantToFieldWhenButtonTapped.

点击按钮时如何在其中写入内容并直接在视图上可见?

您必须

通过在特定单元格的indexPath处调用cellForItem来获取预期的单元格,如下所示:(例如,您的单元格位于第 0 部分第 0 项中(

let indexPath = IndexPath(item: 0, section: 0)
let cell = collectionView.cellForItem(at: indexPath) as? YourCustomCollectionViewCellClass

然后你可以访问你的单元格类中的变量:

cell.myTextFielThatIWantToFieldWhenButtonTapped

最新更新