iOS学习:表视图(二)

上一篇简单介绍了表视图的一些基本概念,这一篇来做一个小小的Demo。
表视图的加载顺序是当视图控制器加载表视图时访问数据源方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
获得单元格数量;然后访问数据源方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
获得每个单元格的数据。然后访问初始化方法:

-initWithFrame:style:

初始化创建单元格。
下面这个Demo创建了一个表视图,用来显示一串数据,数据中包含一个图片和一段描述图片的文字:
界面如下:

iOS学习:表视图(二)_第1张图片
Paste_Image.png

这里创建的时候在表视图属性检查器中有一个Content属性,它可以选择一个动态表和静态表,这个属性只有在故事板中才有。具体的在后面会介绍。同时在这个属性后面有一个Prototype Cells,这个是原型单元格,给予id后可以在初始化单元格的时候调用,以用于重用。注意只能设置为一个,设置为两个的话会出现错误。
代码实现如下:

@interface ViewController () 
@property(nonatomic,strong)NSArray *listTeams; //单元格数据数组
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //将plist文件解析,获得单元格数据数组
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"team.plist" ofType:nil];
    self.listTeams = [[NSArray alloc]initWithContentsOfFile:filePath];
}

#pragma mark - tableViewDataSourse
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //返回单元格数量
    return self.listTeams.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //为每个单元格添加数据
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    //默认情况下单元格主视图样式为在最左边有一个ImageView,挨着有一个Label
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSDictionary *data = self.listTeams[indexPath.row];
    cell.textLabel.text = data[@"name"];
    cell.imageView.image = [UIImage imageNamed:data[@"image"]];
    return cell;
}
@end

你可能感兴趣的:(iOS学习:表视图(二))