How To: Programatically Select a Random Cell in a UITableView

This little snippet of code shows how you can select a random UITableViewCell in a UITableView programatically. For example, you might want to trigger a random selection when the user shakes the device, or through some other action of your determination. Here I assume your familiarity with setting up a UITableView and implementing its associated delegate and datasource methods.

@interface MyTableViewController : UITableViewController {

// Declare arrays in @interface

    NSArray *section1;
    NSArray *section2;
    NSArray *section3;

    NSArray *randomSectionsArray;
}

- (void)viewDidLoad {

// Initialize arrays
    section1 = @[string1, string2, string3];
    section2 = @[string4, string5, string6]:
    section3 = @[string7, string8, string9];

    sectionsArray  = @[section1, section2,
    section3];
}

/* After implementing the delegate and datasource methods for the UITableView, 
   you can now implement the method to select a UITableViewCell at a random indexPath: */

- (void)selectCellAtRandomIndexPath
{
    int randomSectionIndex = arc4random() % sectionsArray.count;

    NSArray *randomSection = sectionsArray[randomSectionIndex];
    int randomRow = arc4random() % randomSection.count;

    NSIndexPath *randomIndexPath = [NSIndexPath 
    indexPathForRow:randomRow inSection:randomSection];

    [self.tableView selectRowAtIndexPath animated:NO
    scrollPosition:UITableViewScrollPositionMiddle];

    [self.tableView.delegate tableView:self.tableView
    didSelectRowAtIndexPath:[self.tableView indexPathForSelectedRow];

}


- (void)triggerAction
{
   //  Now, you can use your trigger action to select a random cell.

    [self selectCellAtRandomIndexPath];
}

That’s it! Happy coding.

Advertisements

One thought on “How To: Programatically Select a Random Cell in a UITableView

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s