365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

May 10

Day 50: Guest post 2, NSResponder goodies

Today’s post was submitted to me some time ago by Vadim Shpakovski from snippetsapp.com. My apologies that it has taken so long to post it, but I am grateful that he wanted to contribute here. So without further ado:

Snow Leopard brought a lot of new APIs that make cool things possible in just a few lines of code. For example, NSResponder class has got a new method named swipeWithEvent:. This method is passed through the first responder chain when you make a 3-fingers swipe gesture on your Multitouch Trackpad or Magic Mouse.

Apple’s Mail.app has one of the most handful implementations for this gesture: 3-fingers swipe allows you to scroll between emails in the main table view. And now you can incorporate this behavior into your Cocoa application really easy. Simply add the following snippet of code to the window controller having a table view:

- (void)handleSwipeBySelectingNextItem:(BOOL)selectNext
{
    // Select next or previous item in the table view
    NSArrayController *listingController = [self dataArrayController];
    if (selectNext)
        [listingController selectNext:self];
    else
        [listingController selectPrevious:self];
    
    // Move selection at the table view and make selected row visible
    NSTableView *listingView = [self dataTableView];
    [self.window makeFirstResponder:listingView];
    [self performSelector:@selector(scrollTableViewToVisibleRow:)
               withObject:listingView afterDelay:0.0f];
}

- (void)scrollTableViewToVisibleRow:(NSTableView *)tableView
{
    [tableView scrollRowToVisible:[tableView selectedRow]];
}

- (void)swipeWithEvent:(NSEvent *)event
{
    if ([event deltaX] < 0 || [event deltaY] < 0)
        [self handleSwipeBySelectingNextItem:YES];
    else if ([event deltaX] > 0 || [event deltaY] > 0)
        [self handleSwipeBySelectingNextItem:NO];
    else
        [super swipeWithEvent:event];
}


  1. 365cocoa posted this