【UIKit】UITableView 2

UITableView 代码

 

【1】拖入一个UITableView

【2】将TableView的dataSource与控制器连接

【3】首先得遵循UITableView的数据源协议<UITableViewDataSource>

【4】将数据plist文件拖入 【资源下载】

    

【5】代码

1.viewDidLoad只加载一次,所以用来加载plist文件中的数据。

  新建一个bundel用来指定文件路径

  pathForResource:文件名
  ofType:文件格式
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSBundle *bundle=[NSBundle mainBundle]; // 获取路径的方法
    // 加载数据
    self.provinces=[NSArray arrayWithContentsOfFile:[bundle pathForResource:@"provinces" ofType:@"plist"]];// 获取路径需要上面的bundle
    self.cities=[NSDictionary dictionaryWithContentsOfFile:[bundle pathForResource:@"cities" ofType:@"plist"]];// 获取路径需要上面的bundle
}

 

2.设置组数,通过对provinces.plist文件中省份的count,来返回一共有多少组

#pragma mark -数据源方法
#pragma mark 一共多少组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // 返回省份的个数,也就是多少组
    return self.provinces.count;
}

3.设置第section组有多少行(先得到第i个组,通过这个组到数组中去调取有多少行,返回对应城市行数)

  首先要设置property

@interface ViewController ()
// 省份
@property(nonatomic,strong)NSArray *provinces;
// 城市
@property (nonatomic,strong)NSDictionary *cities;

@end
#pragma mark 第section组有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 返回省对应城市的成员个数
        // 取出第section组的省份名称
    NSString *pName=self.provinces[section];
        // 取出对应城市
    NSArray *myCities=self.cities[pName];
        // 返回对应城市成员个数
    return myCities.count;
    
}

4.用来返回某一行对应的数据

#pragma mark 返回某一行对应的数据
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   // 创建一个cell
    // UITableViewCellStyleDefault 是默认的style
    // reuseIdentifier 标识符默认为nil
    UITableViewCell *cell=[[UITableViewCell alloc]
                           initWithStyle:UITableViewCellStyleDefault
                           reuseIdentifier:nil];
   // 1.首先取出第section组的省份名称
    NSString *pName= self.provinces[indexPath.section];
   
    // 2.根据上面取出的省份名称来取出这个省份的所有城市
    NSArray *myCities=self.cities[pName];

    // 取出对应的城市名称
    cell.textLabel.text=myCities[indexPath.row];
    
    return cell;
}

5.返回头部标题

#pragma mark 返回头部标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.provinces[section];
}

6.返回索引【此处是使用省份作为索引,如果用拼音首字母作为索引的话,需要调取第三方内容】

#pragma mark -添加索引条,标题索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    //return @[@"A",@"B",@"C"];
    // 返回所有省份
    return self.provinces;
}

 

 

posted @ 2014-04-15 21:29  太过于漂流  阅读(171)  评论(0编辑  收藏  举报