Sian 发表于 2014-3-31 22:59:02

ios实战开发之UITableView

1、效果演示

http://player.youku.com/player.php/sid/XNjkyNzg2MjAw/v.swf

2、过程分析

2.1 创建一个UITableView
2.2 设置UITableView的数据源为当前控制器
2.3 当前控制器遵守UITableViewDataSource协议并实现以下几个方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
3、关键代码
SAViewController.m
//
//SAViewController.m
//UITableView
//
//Created by yusian on 14-3-31.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import "SAViewController.h"

// 定义几个宏
#define kFile   @"address.plist"
#define kUrl    @"http://yusian.com/download/data/address.plist"
#define kHeader @"province"
#define kCities @"cities"
#define kFooter @"description"

@interface SAViewController () <UITableViewDataSource>
{
    NSArray *_addressBook;
}

@end

@implementation SAViewController

- (void)viewDidLoad
{
    ;
   
    // 创建一个UITableView初始化为组模式,并将当前控制器设置为数据源(代理)
    UITableView *tableView = [ initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    ;
    tableView.dataSource = self;
   
    // 准备本地数据,从本地文件读取数据到数组(该数组为多维数据,plist文件事按照相关格式存储数据
    // plist文件格式为NSArray、NSDictionary...]
    // 解释:数组基本元素为字典(一个省份),每个字典里面包含三个对象,两个字符串(该省名称和描述信息)和一个数组(该省份的城市);
    NSString *path = [ pathForResource:kFile ofType:nil];
    _addressBook = [ initWithContentsOfFile:path];   // 加载本地文件到数组_addressBook
   
    // 准备互联网数据,通过url从互联网下载plist文件;
    // NSURL *url = ;
    // _addressBook = [ initWithContentsOfURL:url];
}

// UITableViewDataSource协议中的方法,返回TabelView组数,默认无实现则为1,数组长度即省份数,即分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _addressBook.count;
}

// UITableViewDataSource协议中必须实现的两个方法之一,返回每组的行数,这里即各省份的城市数,所以取各字典中子数组的长度
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return count];
}

// UITableViewDataSource协议中必须实现的两个方法之一,给UITable中cell元素赋值,这里以cell的textLable.text为例
// 通过textLabel的text属性,将每个城市显示在UITable中
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [ initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.textLabel.text = _addressBook;
    return cell;
}

// 定义每个组的Header,即省份名称
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return _addressBook;
}

// 定义每个组的Footer,即省份描述
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return _addressBook;
}
@end

4、源代码下载
**** Hidden Message *****
页: [1]
查看完整版本: ios实战开发之UITableView