从现在开始进入表视图UITableView,同属UISrollView子类。
包括两个协议UITableViewDelegate, UITableViewDataSource
有一些概念
- 表头视图 header view
- 表脚视图 footer view
- 单元格 cell
- 节 section
- 节头 section header
- 节脚 section footer
这里有一个可重复定义对象的概念,这是为了节约内存开销而设计,当屏幕翻动时,旧的单元格退出屏幕,新的进入。
如果每次都实例化cell,会增加内存开销。
使用可充用单元格标识去视图中找,找到久使用,没找到就创建。
//
// ViewController.m
// SimpleTable
//
// Created by 李亚坤 on 14/10/23.
// Copyright (c) 2014年 李亚坤. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"team" ofType:@"plist"];
// 获取表中所有数据
self.listTeams = [[NSArray alloc] initWithContentsOfFile: plistPath];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark DataSource协议中的方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// 返回目前节的行数
return [self.listTeams count];
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 为单元格实现数据
static NSString *CellIdentifier = @"CellIdentifier";
// 这里为可重复用的对象
// 定义为CellIdentifier
// 这样就避免重复定义
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// 如果没有在故事板中定义Cell的identifier,就会触发if
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// 获取名字
// 得到当前行索引数
NSUInteger row = [indexPath row];
NSDictionary *rowDict = [self.listTeams objectAtIndex:row];
cell.textLabel.text = [rowDict objectForKey: @"name"];
// 获取图片
NSString *imagePath = [rowDict objectForKey:@"image"];
imagePath = [imagePath stringByAppendingString:@".png"];
cell.imageView.image = [UIImage imageNamed:imagePath];
// 扩展箭头向右
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
@end
另外,我在使用时,常常出现程序异常退出,错误信息是:原文:http://blog.csdn.net/liyakun1990/article/details/40403783