UITableView的基础部分内容
UITableView的基本设置
#import "MainViewController.h"
#import "SecondViewController.h"
@interface MainViewController ()
<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)NSMutableArray *arr;
@end
@implementation MainViewController
-(void)dealloc{
[_arr release];
[super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.arr = [NSMutableArray arrayWithObjects:@"宋江", @"卢俊义", @"吴用", @"公孙胜", @"关胜", @"林冲", @"秦明" ,@"呼延灼" , @"花荣",@"柴进", @"李应", @"朱仝",@"鲁智深",@"武松",nil];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
[self.view addSubview:tableView];
[tableView release];
tableView.rowHeight = 100;
tableView.dataSource = self;
tableView.delegate = self;
}
#pragma mark tableview第一个必须实现的协议方法,指定分区内有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (section % 2 == 0) {
return 10;
}
if (section % 2 != 0) {
return 5;
}
return self.arr.count;
}
#pragma mark 第二个必须实现的协议方法,主要是用来显示数据
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *reuse = @"reuse";
UITableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:reuse];
if (!cell) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse]autorelease];
}
cell.textLabel.text = self.arr[indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld",indexPath.section];
cell.imageView.image = [UIImage imageNamed:@"456.jpg"];
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"水浒";
}
#pragma mark tableview里有多少个section
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 10;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"];
}
#pragma mark tableview的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"section:%ld, row:%ld",indexPath.section, indexPath.row);
NSLog(@"%@",self.arr[indexPath.row]);
SecondViewController *secVC = [[SecondViewController alloc]init];
[self.navigationController pushViewController:secVC animated:YES];
[secVC release];
}