Я хотел бы выяснить, как распечатать indexPath UICollectionViewCell, когда я долгое время нажимаю на ячейку.
Как я могу сделать это в Swift?
Я рассмотрел пример того, как это сделать; не может найти его в Swift.
Я хотел бы выяснить, как распечатать indexPath UICollectionViewCell, когда я долгое время нажимаю на ячейку.
Как я могу сделать это в Swift?
Я рассмотрел пример того, как это сделать; не может найти его в Swift.
Сначала вы должны быть UIGestureRecognizerDelegate
. Затем добавьте UILongPressGestureRecognizer в свой CollectionView в вашем методе viewcontroller viewDidLoad()
class ViewController: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let lpgr = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
lpgr.minimumPressDuration = 0.5
lpgr.delaysTouchesBegan = true
lpgr.delegate = self
self.collectionView.addGestureRecognizer(lpgr)
}
Метод обработки длинного нажатия:
func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
if gestureReconizer.state != UIGestureRecognizerState.Ended {
return
}
let p = gestureReconizer.locationInView(self.collectionView)
let indexPath = self.collectionView.indexPathForItemAtPoint(p)
if let index = indexPath {
var cell = self.collectionView.cellForItemAtIndexPath(index)
// do stuff with your cell, for example print the indexPath
println(index.row)
} else {
println("Could not find index path")
}
}
Этот код основан на Objective-C версии этого ответа.
Ответ ztan преобразован в быстрый синтаксис 3 и незначительное обновление орфографии:
func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state != UIGestureRecognizerState.ended {
return
}
let p = gestureRecognizer.location(in: collectionView)
let indexPath = collectionView.indexPathForItem(at: p)
if let index = indexPath {
var cell = collectionView.cellForItem(at: index)
// do stuff with your cell, for example print the indexPath
print(index.row)
} else {
print("Could not find index path")
}
}
Метод handleLongProgress, преобразованный в синтаксис swift 3, отлично работает. Я просто хочу добавить, что инициализация lpgr следует изменить на:
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gestureReconizer:)))
Я обнаружил, что:
if gestureReconizer.state != UIGestureRecognizerState.Ended {
return
}
не помещает булавку до тех пор, пока вы не отпустите длинную кнопку, которая в порядке, но я обнаружил
if gestureRecognizer.state == UIGestureRecognizerState.Began { }
вокруг всей функции предотвратит многократное размещение контактов, позволяя вывести вывод, как только будет достигнута задержка таймера.
Кроме того, одна опечатка выше: Reconizer → Recognizer
Swift 5 & Swift 4 Ячейка Табличного Представления
override func viewDidLoad() {
//MARK:- Add Long Gesture
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
longPressGesture.minimumPressDuration = 1.0 // 1 second press
longPressGesture.allowableMovement = 15 // 15 points
longPressGesture.delegate = self
self.tablev.addGestureRecognizer(longPressGesture)
}
//MARK:- Long Press Gesture
@objc func longPressed(sender: UILongPressGestureRecognizer)
{
if sender.state == UIGestureRecognizer.State.ended {
return
}
else if sender.state == UIGestureRecognizer.State.began
{
let p = sender.location(in: self.tablev)
let indexPath = self.tablev.indexPathForRow(at: p)
if let index = indexPath {
var cell = self.tablev.cellForRow(at: index)
// do stuff with your cell, for example print the indexPath
print(index.row)
print("longpressed Tag: \(index.row)")
} else {
print("Could not find index path")
}
}
}
Ответ ztan преобразован в быстрый синтаксис 4 и незначительное обновление орфографии:
@objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
guard gestureRecognizer.state != .ended else { return }
let point = gestureRecognizer.location(in: collectionView)
if let indexPath = collectionView.indexPathForItem(at: point),
let cell = collectionView.cellForItem(at: indexPath) {
// do stuff with your cell, for example print the indexPath
print(indexPath.row)
} else {
print("Could not find index path")
}
}