如何在不使用didSelectItemAtIndexPath和prepareForSegue的情况下查找所选Collection View Cell的索引路径?
我在AlertViewController中使用此indexPath。我不知道如何在AlertView控制器中获取此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)
答案 0 :(得分:2)
使用此:
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 :(得分: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 :(得分:1)
这是我的解决方法
private func getCurrentIndex() -> Int {
return Int(collectionView.contentOffset.x / collectionView.frame.width)
}
答案 3 :(得分: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
}
希望它能奏效。
答案 4 :(得分:-2)
在CollectionView委托调用中
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
print(" Row : \(indexPath.row)")
return cell
}