Skip to content

Instantly share code, notes, and snippets.

@switz
Last active August 29, 2015 14:13
Show Gist options
  • Save switz/0bc0e75598ed4884cba5 to your computer and use it in GitHub Desktop.
Save switz/0bc0e75598ed4884cba5 to your computer and use it in GitHub Desktop.
class ContainerViewController: UIViewController, UITableViewDelegate, NSFetchedResultsControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Play on touch down
var td = UILongPressGestureRecognizer(target: self, action: "touchDown:")
td.minimumPressDuration = 0;
td.allowableMovement = 10000;
self.table.addGestureRecognizer(td);
}
func touchDown(gesture: UIGestureRecognizer) {
if (gesture.state == UIGestureRecognizerState.Ended) {
if self.playerViewController != nil {
self.playerViewController!.dismissViewControllerAnimated(false, completion: nil);
}
}
if (gesture.state != UIGestureRecognizerState.Began) { return; }
let fingerLocation = gesture.locationInView(self.table);
if let indexPath = self.table.indexPathForRowAtPoint(fingerLocation) {
let container = self.fetchedResultsController?.objectAtIndexPath(indexPath) as NSManagedObject
// do stuff with container
self.performSegueWithIdentifier("show_player", sender: self);
}
}
}
@lilyball
Copy link

I'd recommend something like this:

// touchDown is not an appropriate name now that this handles all touch events
func tableRecognizer(gesture: UIGestureRecognizer) {
    switch gesture.state {
    case .Began:
        let fingerLocation = gesture.locationInView(self.table)
        if let indexPath = self.table.indexPathForRowAtPoint(fingerLocation) {
            // you're doing an unconditional type-cast here, which will fail if
            // self.fetchedResultsController is nil. You should either use
            // `as? NSManagedObject` or `as NSManagedObject?`, with the latter
            // failing if the object is non-nil but not an NSManagedObject and
            // the former returning nil in that case.
            // If you're confident assuming that self.fetchedResultsController
            // is non-nil, then you might want to use ! instead to indicate
            // that.
            let container = self.fetchedResultsController?.objectAtIndexPath(indexPath) as NSManagedObject
            // do stuff with container
            self.performSegueWithIdentifier("show_player", sender: self)
        }
    case .Ended, .Cancelled:
        // note that we're responding to both .Ended AND .Cancelled, otherwise
        // cancelled touches (e.g. because of phone calls) won't dismiss the
        // view controller.
        self.playerViewController?.dismissViewControllerAnimated(false, completion: nil)
    default:
        // we don't want to handle other events
        () // we need some expression, () is the standard expression that means no value.
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment