【问题标题】:Tap on cell and get index点击单元格并获取索引
【发布时间】:2015-11-09 18:58:33
【问题描述】:

当我点击一个单元格时,我想接收特定于该单元格的索引或其他标识符。该代码有效并进入点击功能。但是我怎样才能收到索引或类似的东西呢?

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ShowCell", forIndexPath: indexPath) as UICollectionViewCell

    if cell.gestureRecognizers?.count == nil {
        let tap = UITapGestureRecognizer(target: self, action: "tapped:")
        tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
        cell.addGestureRecognizer(tap)
    }

    return cell
}

func tapped(sender: UITapGestureRecognizer) {
    print("tap")  
}

【问题讨论】:

标签: swift


【解决方案1】:

Swift 4 - 4.2 - 返回点击单元格的索引。

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cellIndex = indexPath[1] // try without [1] returns a list.
print(indexPath[1])
chapterIndexDelegate.didTapChapterSelection(chapterIndex: test)
}

【讨论】:

    【解决方案2】:

    基于 Matts 的答案

    首先我们添加点击识别器

    let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapped(tapGestureRecognizer:)))
    cell.textView.addGestureRecognizer(tap)
    

    然后我们使用下面的函数来获取indexPath

    @objc func tapped(tapGestureRecognizer: UITapGestureRecognizer){
        //textField or what ever view you decide to have the tap recogniser on
        if let textField = tapGestureRecognizer.view as? UITextField {
    
            // get the cell from the textfields superview.superview
            // textField.superView would return the content view within the cell
            if let cell = textField.superview?.superview  as? UITableViewCell{
    
                // tableview we defined either in storyboard or globally at top of the class
    
                guard let indexPath = self.tableView.indexPath(for: cell) else {return}
                print("index path =\(indexPath)")
    
    // then finally if you wanted to pass the indexPath to the main tableView Delegate
    
                    self.tableView(self.tableView, didSelectRowAt: indexPath)
    
                }
        }
    }
    

    【讨论】:

      【解决方案3】:

      考虑一下。 sender 是点击手势识别器。 g.r. 的 view 是单元格。现在你可以询问collection view这个cell的索引路径是什么(indexPathForCell:)。

      【讨论】:

      • 是类似于 sender.view 之类的吗?
      • 当您确切知道要粘贴什么代码时,您故意避免进一步帮助他们。他们付出了努力。
      • 如果手势识别器的视图是单元格的子视图怎么办?如果您重新安排布局,则在代码中沿着视图层次结构查找单元格有点脆弱。虽然这在技术上可能是正确的,但它有点令人不满意。
      • @RobertAtkins 我不同意。
      猜你喜欢
      • 2017-02-08
      • 2013-06-24
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多