UITableView是iOS中最常用的控件了,所以使用起来也很简单。
ViewContoller.h 文件 (继承UITableViewDelegate&UITableViewDataSource协议):
//
// ViewController.h
// ViewController
//
// Created by monkey mot on 13-6-20.
// Copyright (c) 2013年 monkey mot. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *mytable;
@end
ViewController.m 实现协议来呈现tableView :
//
// ViewController.m
// ViewController
//
// Created by monkey mot on 13-6-20.
// Copyright (c) 2013年 monkey mot. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
self.mytable =
[[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.mytable.delegate = self;
self.mytable.dataSource = self;
//self.mytable.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.mytable];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 5;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5000;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *result = nil;
if( [tableView isEqual:self.mytable]) {
static NSString *cellIdentifier = @"Cells";
result = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if( result == nil) {
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
result.textLabel.text = [NSString stringWithFormat:@"Section %ld Cell %ld",
(long)indexPath.section , (long)indexPath.row];
}
return result;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if( [tableView isEqual:self.mytable] == NO)
return ;
[[tableView cellForRowAtIndexPath:indexPath] setBackgroundColor: [UIColor redColor]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"cell is selected"
message: [NSString stringWithFormat:@"cell is %ld",(long)indexPath.row]
delegate: nil
cancelButtonTitle: @"close"
otherButtonTitles: nil];
[alert show];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if( [tableView isEqual:self.mytable]) {
return @"This is my table section";
}
return @"";
}
@end
run一下 会出现table 跟 cell 点击相应的cell 能触发事件