Подтвердить что ты не робот

Как выбрать строку таблицы во время длительного нажатия в Swift

У меня есть таблица, в которой есть длинный распознаватель жестов нажатия, который запускает код в зависимости от того, какая строка таблицы выбрана.

Проблема, с которой я столкнулась, заключается в том, что в настоящее время мне нужно нажать на строку, которую я хочу, а затем сделать длинную печать.

Как я могу заставить таблицу выбрать строку, которую я долго нажимаю, не нажимая, чтобы выбрать ее первым?

4b9b3361

Ответ 1

Следующий код отлично подходит для меня:

Добавьте длинный идентификатор распознавания жестов в viewDidLoad:

// tapRecognizer, placed in viewDidLoad
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPress:")
self.view.addGestureRecognizer(longPressRecognizer)

Затем метод, вызываемый длинным нажатием, выглядит следующим образом:

//Called, when long press occurred
func longPress(longPressGestureRecognizer: UILongPressGestureRecognizer) {

    if longPressGestureRecognizer.state == UIGestureRecognizerState.Began {

        let touchPoint = longPressGestureRecognizer.locationInView(self.view)
        if let indexPath = tableView.indexPathForRowAtPoint(touchPoint) {

            // your code here, get the row for the indexPath or do whatever you want
    }
}

Ответ 2

Функция Swift 3:

func handleLongPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {

    if longPressGestureRecognizer.state == UIGestureRecognizerState.Began {

        let touchPoint = longPressGestureRecognizer.locationInView(self.view)
        if let indexPath = tableView.indexPathForRowAtPoint(touchPoint) {

            // your code here, get the row for the indexPath or do whatever you want
    }
}

viewDidLoad:

let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(YourViewController.handleLongPress(_:)))
longPressGesture.minimumPressDuration = 1.0 // 1 second press
longPressGesture.delegate = self
self.tableView.addGestureRecognizer(longPressGesture)

Подробнее: https://github.com/apple/swift-evolution/blob/e4328889a9643100177aef19f6f428855c5d0cf2/proposals/0046-first-label.md

Ответ 3

Swift 4

override func viewDidLoad() {
    super.viewDidLoad()
    setupLongPressGesture()
}

func setupLongPressGesture() {
    let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPress))
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.delegate = self
    self.tblMessage.addGestureRecognizer(longPressGesture)
}

@objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer){
    if gestureRecognizer.state == .ended {
        let touchPoint = gestureRecognizer.location(in: self.tblMessage)
        if let indexPath = tblMessage.indexPathForRow(at: touchPoint) {

        }
    }
}

Свифт 3

override func viewDidLoad() {
    super.viewDidLoad()
    setupLongPressGesture()
}

func setupLongPressGesture() {
    let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(YourViewController.handleLongPress(_:)))
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.delegate = self
    self.tblMessage.addGestureRecognizer(longPressGesture)
}

func handleLongPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {

    if longPressGestureRecognizer.state == UIGestureRecognizerState.Began {

        let touchPoint = longPressGestureRecognizer.locationInView(self.view)
        if let indexPath = tableView.indexPathForRowAtPoint(touchPoint) {

            // your code here, get the row for the indexPath or do whatever you want
        }
    }
}

Цель - С

UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPress:)];
[self.tableView addGestureRecognizer:longPressRecognizer];

-(void)onLongPress:(UILongPressGestureRecognizer*)pGesture
{
    if (pGesture.state == UIGestureRecognizerStateRecognized)
    {
    //Do something to tell the user!
    }

    if (pGesture.state == UIGestureRecognizerStateEnded)
    {
        UITableView* tableView = (UITableView*)self.view;
        CGPoint touchPoint = [pGesture locationInView:self.view];
        NSIndexPath* row = [tableView indexPathForRowAtPoint:touchPoint];
        if (row != nil) {
        //Handle the long press on row
        }
    }
}

Ответ 4

Swift 4

let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(sender:)))
self.view.addGestureRecognizer(longPressRecognizer)

//MARK: действия

@objc func longPressed(sender: UILongPressGestureRecognizer) {

    if sender.state == UIGestureRecognizerState.began {

        let touchPoint = sender.location(in: self.tableView)
        if let indexPath = tableView.indexPathForRow(at: touchPoint) {

            print("Long pressed row: \(indexPath.row)")
        }
    }
}

Ответ 5

Для Версии 3 быстрого

func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
    if longPressGestureRecognizer.state == UIGestureRecognizerState.began {
        let touchPoint = longPressGestureRecognizer.location(in: self.view)
        if let indexPath = notificationTabelView.indexPathForRow(at: touchPoint) {
            print("indexPath=\(indexPath)")
            // your code here, get the row for the indexPath or do whatever you want
        }
    }
}

В вашей функции viewDidLoad

let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(EmployeeNotificationViewController.longPress(_:)))
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.delegate = self as? UIGestureRecognizerDelegate
    self.notificationTabelView.addGestureRecognizer(longPressGesture)

Ответ 6

Чтобы этого избежать, вы можете добавить UILongPressGestureRecognizer внутри cellForRowAtIndexPath вместо didSelectRowAtIndexPath

Ответ 7

Используя IBAction, вы можете сделать (для CollectionView):

@IBAction func handleLongPress(sender: AnyObject) {

    if sender.state == UIGestureRecognizerState.Began
    {
        let position = sender.locationInView(sender.view)

        if let indexPath : NSIndexPath = ((sender.view as! UICollectionView).indexPathForItemAtPoint(position))!{
            print("You holding cell #\(indexPath.item)!")
        }
    }
}

Не забудьте связать свой рекордер жестов с длинным нажатием.

Ответ 8

let longPressGesture = UILongPressGestureRecognizer(target: self, action: (#selector(YourCustomeTableCell.longTap)))
self.addGestureRecognizer(longPressGesture)

func longTap(){
    print("Long tap")
}