列表视图可以说是移动app中最常用的空间,IOS中有UITableView和UICollectionView,UITableView类似Android中的ListView,而UICollectionView类似Android中的GridView。
这里简单学习UITableView的使用方法。
1.首先在xib(xcode7以后其实一般推荐使用storyboard)中添加一table view 和table view cell,同时对table view cell设置reuse identifier:
2.选中table view按住ctrl键,移动鼠标到TmpViewController.h文件相应位置,添加UITableView的成员,同时手动添加相关代理
@interface TmpViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>{
NSMutableArray *mData;
IBOutlet UITableView *mTableVIew;
}
同时不要忘了,选中table view右键后,关联datasource和delegae到file ower中:
2. 定义资源:
- (void)viewDidLoad {
[super viewDidLoad];
mData = [[NSMutableArray alloc]initWithObjects:@"Data 1",@"Data 2",@"Data 3",@"Data 4",@"Data 5",@"Data 6",@"Data 7",@"Data 9",@"Data 9",@"Data 10",nil];
}
- 然后就是table view代理的实现了(IOS代理类似Android中的listener接口):
1)tableview分段定义:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [mData count]/2;
}
2)TableViewCell的实现:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"myDataCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
NSString *cellString;
if(indexPath.section == 0) {
cellString = [mData objectAtIndex:indexPath.row];
} else if(indexPath.section == 1) {
cellString = [mData objectAtIndex:indexPath.row + [mData count]/2];
}
[cell.textLabel setText:cellString];
return cell;
}
3)标头和标脚:
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString *header;
if(section == 0){
header = @"Header 0";
} else if(section == 1) {
header = @"Header 1";
}
return header;
}
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
NSString *footer;
if(section == 0){
footer = @"Footer 0";
} else if(section == 1) {
footer = @"Footer 1";
}
return footer;
}
4)点击事件:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Section:%ld Row:%ld selected and its data is %@", indexPath.section,indexPath.row,cell.textLabel.text);
}
- 效果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)