Как найти индексный путь для выбранной ячейки представления коллекции?
Как найти индексный путь для выбранной ячейки представления коллекции, не используя didSelectItemAtIndexPath и prepareForSegue?
Я использую этот indexPath в AlertViewController. Я не знаю, как получить этот indexPath в контроллере AlertView.
//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)
3 ответа
Использовать этот:
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 {
}
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)
}
Вот мое решение
private func getCurrentIndex() -> Int {
return Int(collectionView.contentOffset.x / collectionView.frame.width)
}
Чтобы выбрать ячейку без метода 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
}
Надеюсь, это сработает.
Внутри вашего вызова делегата CollectionView
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
print(" Row : \(indexPath.row)")
return cell
}