您的位置:首页 > 产品设计 > UI/UE

(4) IOS笔记本——UITableView的基本应用

2016-03-09 10:31 453 查看
◇UITableView继承自UIScrollView,因此支持垂直滚动,而且性能极佳,在特定情况下我们使用UIScrollView而不是UITableView。

◇UITableView通过一个数据源(dataSource)来显示数据,会向数据源查询一共有多少行数据,以显示什么数据。

◇举一个小例子,我们要做如下图的的一个下拉表格:



◇步骤为:

    ◇1、利用MVC的设计模式建立模型,(MVC的思想:只要修改了模型,视图界面一并跟着修改)

    ◇2、准守协议,设置模型数据

    ◇3、设置UITableView的各个属性,并且绑定数据源

◇具体实现方法:

    ◇1、建立模型,新建一个cocoa文件,把下面代码写在.h文件的定义(@interface)中

//用于描述标题
@property (nonatomic,copy) NSString *title;

//用于描述详细描述
@property (nonatomic,copy) NSString *desc;

//用于存放汽车品牌
@property (nonatomic,strong) NSArray *car;


    ◇2、准守协议,设置模型数据

@interface ViewController () <UITableViewDataSource>  //准守协议
。。。 。。。 。。。
@property (nonatomic,strong) NSArray *carGroups;//定义数组变量
。。。 。。。 。。。
//设置模型数组
-(NSArray *)carGroups{
if(_carGroups == nil){

//德系品牌
CarGroup *cg1 = [[CarGroup alloc] init];
cg1.title = @"德系品牌";
cg1.desc = @"德国品牌德国品牌德国品牌德国品牌";
cg1.car = @[@"大众",@"奔驰",@"奥迪"];

//日系品牌
CarGroup *cg2 = [[CarGroup alloc] init];
cg2.title = @"日系品牌";
cg2.desc = @"日系品牌日系品牌日系品牌日系品牌";
cg2.car = @[@"丰田",@"本田",@"因菲妮迪"];

//欧系品牌
CarGroup *cg3 = [[CarGroup alloc] init];
cg3.title = @"欧系品牌";
cg3.desc = @"欧系品牌欧系品牌欧系品牌欧系品牌";
cg3.car = @[@"劳斯莱斯",@"兰博基尼",@"宾利",@"劳斯莱斯",@"兰博基尼",@"宾利"];

_carGroups = @[cg1, cg2, cg3];
}
return _carGroups;
}


    ◇3、设置UITableView的各个属性,并且绑定数据源

//设置一共有多少组数据
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return self.carGroups.count;
}

//设置每组数据有多少行信息
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
CarGroup *cg = self.carGroups[section];
return cg.car.count;
}

//设置每个cell的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

//实例化cell对象
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

// 取出第indexPath.section组对应的模型
CarGroup *cg = self.carGroups[indexPath.section];

// 取车第indexPath.row这行对应的品牌名称
NSString *car = cg.car[indexPath.row];

// 设置cell显示的文字
cell.textLabel.text = car;

return cell;
}


    ◇附一张UITableViewCell的UITableViewCellStyle枚举类型属性图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: