如何为选定的集合视图单元格找到索引路径?

问题描述 投票:0回答:5

如何在不使用didSelectItemAtIndexPath和prepareForSegue的情况下找到选定集合视图单元的索引路径?

我正在AlertViewController中使用此indexPath。我不知道如何在AlertView Controller中获取此indexPath。

//Edit Selected Category
        let alertController = UIAlertController(title: "Alert", message: "Rename your ", preferredStyle: .alert)
        let actionOK = UIAlertAction(title: "OK", style: .default)

        alertController.addTextField(configurationHandler: {(textField: UITextField) -> Void in

            if let iP: IndexPath = self.collCategory.indexPath(for: CategoryCollectionCell) {

                print("IP \(iP)")
            }

        })

        alertController.addAction(actionOK)
        self.present(alertController, animated: true, completion: nil)
ios swift uialertcontroller nsindexpath
5个回答
4
投票

使用此:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .bottom)
}

然后您将从collectionView.indexPathsForSelectedItems获取路径

if let collectionView = self.YourCollectionView,
    let indexPath = collectionView.indexPathsForSelectedItems?.first,
    let cell = collectionView.cellForItem(at: indexPath) as? YourCell {
}

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)
}

0
投票

要选择没有didSelect方法的单元格,则可以使用Tap Gesture来检测单元格。选中以下方法将手势添加到单元格并检测手势。

//将以下代码添加到collectionview单元格返回方法

if let gestures = cell. contentView.gestureRecognizers {
            gestures.forEach({ (tap) in
                if tap .isKind(of: UITapGestureRecognizer.self) == true {
                    cell.contentView.removeGestureRecognizer(tap)
                }
            })
        }
let tapRec = UITapGestureRecognizer.init(target: self, action: #selector(didTap(sender:)))
cell.contentView.isUserInteractionEnabled = true
cell.contentView.addGestureRecognizer(tapRec)

//创建检测手势识别器的方法

func didTap(sender: UIGestureRecognizer)
{
    let cell = sender.view?.superview as! yourCell
}

希望它会起作用。


0
投票

这是我的解决方法

private func getCurrentIndex() -> Int {
    return Int(collectionView.contentOffset.x / collectionView.frame.width)
}

-2
投票

在您的CollectionView委托调用内部

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) 
    print(" Row : \(indexPath.row)")

    return cell
}
© www.soinside.com 2019 - 2024. All rights reserved.