Adding image or text for UILongPressGestureRecognizer in Swift?

136 views Asked by At

So, some of my users don't realize they can hold a cell to get an alert pop-up with options. So, I would like to add some kind of image or text or color - something - to let the user know "hey, you can hold this to get more info." Here is my code below. Any thoughts on the best way to do this?

// handles long press for editing or sharing a search
func tableViewCellLongPressed(
    sender: UILongPressGestureRecognizer) {
        if sender.state == UIGestureRecognizerState.Began &&
            !tableView.editing {
                let cell = sender.view as! UITableViewCell // get cell
                if let indexPath = tableView.indexPathForCell(cell) {
                    displayLongPressOptions(indexPath.row)
                }
        }
}

// displays the edit/share options
func displayLongPressOptions(row: Int) {
    // create UIAlertController for user input
    let alertController = UIAlertController(title: "Helpful Stuff",
        message: "",
        preferredStyle: UIAlertControllerStyle.Alert)

    // create Cancel action
    let cancelAction = UIAlertAction(title: "Cancel",
        style: UIAlertActionStyle.Cancel, handler: nil)
    alertController.addAction(cancelAction)

    let shareAction = UIAlertAction(title: "Share",
        style: UIAlertActionStyle.Default,
        handler: {(action) in self.shareSearch(row)})
    alertController.addAction(shareAction)
    presentViewController(alertController, animated: true,
        completion: nil)
}

// callback that returns a configured cell for the given NSIndexPath
override func tableView(tableView: UITableView,
    cellForRowAtIndexPath indexPath: NSIndexPath) ->
    UITableViewCell {

        // get cell
        let cell = tableView.dequeueReusableCellWithIdentifier(
            "Cell", forIndexPath: indexPath) as UITableViewCell

        // set cell label's text to the tag at the specified index
        cell.textLabel?.text = model.tagAtIndex(indexPath.row)

        // set up long press guesture recognizer
        let longPressGestureRecognizer = UILongPressGestureRecognizer(
            target: self, action: "tableViewCellLongPressed:")
        longPressGestureRecognizer.minimumPressDuration = 0.5
        cell.addGestureRecognizer(longPressGestureRecognizer)

        return cell
}
1

There are 1 answers

0
Peter Hale On

If you want to use the Storyboard, that may be easier to hook up the gesture recognizer and link that to the button in the Storyboard, instead of having it in the cellForRowAtIndexPath, which is called many times