swift - 如何捕获自定义 UICollectionViewCell 的 didSelectItemAt

标签 swift

我有一个自定义的 UICollectionViewCell,上面放置了一个 UITextField。 UICollectionView 中有多个项目和多种类型的单元格,因此,我只想一次只允许一个文本字段的编辑。为此,我尝试在选择单元格时触发单元格自定义类中 UItextField 的变为firstResponder。

从 UICollectionView 脚本“didSelectItemat”获取单元格并不能满足我的要求,因为算法会很拥挤,并且可能有机会调用没有 UITextField 的单元格。

所以我想简单地在 customCell 脚本中编写代码。如果单元格被选中,UITextField 的存储属性将成为 FirstResponder。

我的问题是有没有办法像 UITableViewCell 一样在 CustomCollectionCell 类中选择单元格。

例如)用于获取选择操作的 UITableViewCell 代码

setSelected(_ selected: Bool, animated: Bool) {
    <#code#>
}

我尝试对 self 使用 addGesture,但认为它可能与 UICollectionView 委托(delegate) didSelectItemat 冲突

import UIKit

class RightTextFieldCell: UICollectionViewCell {

    @IBOutlet weak var itemLabel: UILabel!
    @IBOutlet weak var valueTextField: UITextField!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func bind(data: ProfileDoubleStringData) {
        self.itemLabel.text = data.item
        self.valueTextField.text = data.value
    }

}

最佳答案

你可以尝试:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

     let cell = collectionView.cellForItem(at: indexPath) as! MyCell
     cell.doSomething()
}

关于swift - 如何捕获自定义 UICollectionViewCell 的 didSelectItemAt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58052779/

相关文章:

ios - 识别 UITableViewCell 中的 UIButton 不起作用 - Swift

swift - 使用新的 Firebase 登录 Facebook

json - 使用 Codable Protocol 或外部工具进行 JSON 映射

swift - 具有混合类型的 Nil 合并运算符

ios - 与协议(protocol)相关的 SourceKitService 崩溃?

ios - 通过为 Swift 中的每个字符提供两种可能性来比较字符串

swift - NSView 的 mouseMoved 永远不会被调用

ios - 通过触摸外部关闭 iOS 键盘(更聪明的方式)

ios - Firestore iOS 或查询(whereField ("X",在 : ["Y", "Z"])

ios - 在一个 View 中设置两个 UIPickerview