0

I would like to use a long press gesture to toggle an .isHidden property of a tableView. My code (below) makes the tableView appear upon the first long press but does not hide it upon the second long press.

let recognizer = UILongPressGestureRecognizer()
var hideTableView = true
@IBAction func longPress(_ sender: Any) {
    if recognizer.state == .began {
        hideTableView = !hideTableView
    }

    if hideTableView {
        tableView.isHidden = false
        tableView.reloadData()
    }

    if !hideTableView {
        tableView.isHidden = true
    }
}

Any ideas appreciated!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Pat Dolan
  • 41
  • 6

1 Answers1

0

First, you need to move all of the code to inside the if recognizer.state == .began { block.

Next, get rid of the hideTableView property. Simply toggle the isHidden property of the table view. Then reload is it's false after being toggled.

@IBACTION func longPress(_ gesture: UILongPressGestureRecognizer) {
    if gesture.state == .began {
        tableView.isHidden = !tableView.isHidden
        if !tableView.isHidden {
            tableView.reloadData()
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks! Works like a charm. Very elegant. As a further improvement I replaced recognizer.state with sender.state in your second line and forwent constructing a UILongPressGestureRecognizer() – Pat Dolan May 12 '18 at 01:57
  • Oh yeah, I meant to make that change when I updated the parameter. Glad to help. Please don't forget to indicate that your question has been solved by accepting the answer (click the checkmark to the left of the answer). – rmaddy May 12 '18 at 02:23