行へのスナップとともに完全な例(ScrollView Delegateを実装することによる):
ViewController.h:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@end
ViewController.m:
#import "ViewController.h"
static int kRowHeight = 92;
static int kArrayCount = 20;
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray *tableViewData;
@end
@implementation ViewController
-(void)populateArray {
for (int i=0; i<kArrayCount; i++) {
[self.tableViewData addObject:[NSString stringWithFormat:@"String # %d",i]];
}
[self.myTableView reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.tableViewData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.textLabel.text = [self.tableViewData objectAtIndex:indexPath.row];
// Configure the cell...
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
// Standard UIAlert Syntax
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:@"Selected"
message:[NSString stringWithFormat:@"Selected Row %d", indexPath.row]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[myAlert show];
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *indexPaths = [tableView indexPathsForVisibleRows];
if ([[indexPaths objectAtIndex:2] isEqual:indexPath]) {
return indexPath;
} else {
return nil;
}
}
#pragma mark - ScrollView Delegate Methods (Make rows snap to position top)
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetContentOffset {
int cellHeight = kRowHeight;
*targetContentOffset = CGPointMake(targetContentOffset->x,
targetContentOffset->y - (((int)targetContentOffset->y) % cellHeight));
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableViewData = [[NSMutableArray alloc] initWithCapacity:kArrayCount];
[self populateArray];
// Do any additional setup after loading the view, typically from a nib.
}
@end