UITableView基础

2015-11-16  本文已影响128人  Coder_Fsh_Messi

什么是UITableView

UITableView的两种格式

如何创建UITableView

UITableView *myTableView = [UITableView alloc] init];

如何展示数据

tableView展示数据的过程

// 多少组数据
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

// 每一组有多少行数据
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

// 每一行显示什么内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

// 设置每一行cell的高度
self.tableView.rowHeight = 100;
// 设置每一组头部的高度
self.tableView.sectionHeaderHeight = 50;
// 设置每一组尾部的高度
self.tableView.sectionFooterHeight = 50;
// 设置分割线颜色
self.tableView.separatorColor = [UIColor redColor];
// 设置分割线样式
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
// 设置表头控件
self.tableView.tableHeaderView = [[UISwitch alloc] init];
// 设置表尾控件
self.tableView.tableFooterView = [UIButton buttonWithType:UIButtonTypeContactAdd];
// 设置右边索引文字的颜色
self.tableView.sectionIndexColor = [UIColor redColor];
// 设置右边索引文字的背景色
self.tableView.sectionIndexBackgroundColor = [UIColor blackColor];

cell的简介

typedef NS_ENUM(NSInteger, UITableViewCellAccessoryType) {
    UITableViewCellAccessoryNone,                                                      // don't show any accessory view
    UITableViewCellAccessoryDisclosureIndicator,                                       // regular chevron. doesn't track
    UITableViewCellAccessoryDetailDisclosureButton __TVOS_PROHIBITED,                 // info button w/ chevron. tracks
    UITableViewCellAccessoryCheckmark,                                                 // checkmark. doesn't track
    UITableViewCellAccessoryDetailButton NS_ENUM_AVAILABLE_IOS(7_0)  __TVOS_PROHIBITED // info button. tracks
};

cell的重用原理

/**
 *  每当有一个cell要进入视野范围内,就会调用一次
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // cell的标识
    static NSString *ID = @"wine";
    
    // 先去缓存池中查找可循环利用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    // 如果缓存池中没有可循环利用的cell
    if (!cell) {
        // 自己创建一个cell
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID]
   // 设置cell的属性
     ...
    return cell;
    }
- (void)viewDidLoad {
    [super viewDidLoad];

    // 注册某个重用标识 对应的 Cell类型
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.先去缓存池中查找可循环利用的cell,
   //  如果没有的话,[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID]方法会我们创建

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    // 2.设置数据
    ....

    return cell;
}
上一篇 下一篇

猜你喜欢

热点阅读