UITableView快速入门

​# UITableViewDatasource

设置数据源

  • 设置数据源的对象必须遵守UITableViewDatasource协议
self.tableView.dataSource = self;

必须实现的数据源方法

@required

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

// 设置每一个cell显示什么,长什么样子
// 什么时候调用:每当有一个cell进入视野范围内就会调用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

其它数据源方法

@optional

// 设置有多少组,如果实现此方法,默认返回组数为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

// 设置第section组的头部显示的string
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
// 设置第section组的尾部显示的string
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;

// Editing

// Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.
// 设置每一组是否有可编辑的能力。如果不实现,所有的row假定是可编辑的
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;

// 其它的直接点进头文件看
...

UITableViewDelegate

设置代理

  • 设置的代理对象必须遵守UITableViewDelegate协议
self.tableView.delegate = self;

常见代理方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;

// custom view for header. will be adjusted to default or specified header height
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
// custom view for footer. will be adjusted to default or specified footer height
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;


// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

...

Cell的循环利用方式1

/**
 *  什么时候调用:每当有一个cell进入视野范围内就会调用
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 0.重用标识
    // 被static修饰的局部变量:只会初始化一次,在整个程序运行过程中,只有一份内存
    static NSString *ID = @"cell";

    // 1.先根据cell的标识去缓存池中查找可循环利用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    // 2.如果cell为nil(缓存池找不到对应的cell)
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }

    // 3.覆盖数据
    cell.textLabel.text = [NSString stringWithFormat:@"testdata - %zd", indexPath.row];

    return cell;
}

Cell的循环利用方式2

  • 定义一个全局变量
// 定义重用标识
NSString *ID = @"cell";
  • 注册某个标识对应的cell类型
// 在这个方法中注册cell
- (void)viewDidLoad {
    [super viewDidLoad];

    // 注册某个标识对应的cell类型
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}
  • 在数据源方法中返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.去缓存池中查找cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    // 2.覆盖数据
    cell.textLabel.text = [NSString stringWithFormat:@"testdata - %zd", indexPath.row];

    return cell;
}

Cell的循环利用方式3

  • 在storyboard中设置UITableView的Dynamic Prototypes Cell

  • 设置cell的重用标识

  • 在代码中利用重用标识获取cell

// 0.重用标识
// 被static修饰的局部变量:只会初始化一次,在整个程序运行过程中,只有一份内存
static NSString *ID = @"cell";

// 1.先根据cell的标识去缓存池中查找可循环利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

// 2.覆盖数据
cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd", indexPath.row];

return cell;

自定义cell

  • 等高的cell
    • storyboard自定义cell

      • 1.创建一个继承自UITableViewCell的子类,比如SLDealCell

      • 2.在storyboard中
        • 往cell里面增加需要用到的子控件

        • 设置cell的重用标识

        • 设置cell的class为SLDealCell

      • 3.在控制器中
        • 利用重用标识找到cell
        • 给cell传递模型数据

      • 4.在SLDealCell中
        • 将storyboard中的子控件连线到类扩展中

        • 需要提供一个模型属性,重写模型的set方法,在这个方法中设置模型数据到子控件上


    • xib自定义cell

      • 1.创建一个继承自UITableViewCell的子类,比如SLDealCell
      • 2.创建一个xib文件(文件名建议跟cell的类名一样),比如SLDealCell.xib
        • 拖拽一个UITableViewCell出来
        • 修改cell的class为SLDealCell
        • 设置cell的重用标识
        • 往cell中添加需要用到的子控件
      • 3.在控制器中
        • 利用registerNib...方法注册xib文件
        • 利用重用标识找到cell(如果没有注册xib文件,就需要手动去加载xib文件)
        • 给cell传递模型数据
      • 4.在SLDealCell中
        • 将xib中的子控件连线到类扩展中
        • 需要提供一个模型属性,重写模型的set方法,在这个方法中设置模型数据到子控件上
        • 也可以将创建获得cell的代码封装起来(比如cellWithTableView:方法)
    • 代码自定义cell(使用frame)

      • 1.创建一个继承自UITableViewCell的子类,比如SLDealCell
        • 在initWithStyle:reuseIdentifier:方法中
          • 添加子控件
          • 设置子控件的初始化属性(比如文字颜色、字体)
        • 在layoutSubviews方法中设置子控件的frame
        • 需要提供一个模型属性,重写模型的set方法,在这个方法中设置模型数据到子控件
      • 2.在控制器中
        • 利用registerClass...方法注册SLDealCell类
        • 利用重用标识找到cell(如果没有注册类,就需要手动创建cell)
        • 给cell传递模型数据
        • 也可以将创建获得cell的代码封装起来(比如cellWithTableView:方法)
    • 代码自定义cell(使用autolayout)

      • 1.创建一个继承自UITableViewCell的子类,比如SLDealCell
        • 在initWithStyle:reuseIdentifier:方法中
          • 添加子控件
          • 添加子控件的约束(建议使用Masonry
          • 设置子控件的初始化属性(比如文字颜色、字体)
        • 需要提供一个模型属性,重写模型的set方法,在这个方法中设置模型数据到子控件
      • 2.在控制器中
        • 利用registerClass...方法注册SLDealCell类
        • 利用重用标识找到cell(如果没有注册类,就需要手动创建cell)
        • 给cell传递模型数据
        • 也可以将创建获得cell的代码封装起来(比如cellWithTableView:方法)

UITableViewCell的常见设置

// 取消选中的样式
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// 设置选中的背景色
UIView *selectedBackgroundView = [[UIView alloc] init];
selectedBackgroundView.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = selectedBackgroundView;

// 设置默认的背景色
cell.backgroundColor = [UIColor blueColor];

// 设置默认的背景色
UIView *backgroundView = [[UIView alloc] init];
backgroundView.backgroundColor = [UIColor greenColor];
cell.backgroundView = backgroundView;

// backgroundView的优先级 > backgroundColor
// 设置指示器
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.accessoryView = [[UISwitch alloc] init];

强制刷新布局

[self layoutIfNeed];

方法调用顺序

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"cellForRowAtIndexPath");
    ...
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%s", __func__);
    return [self.statues[indexPath.row] cellHeigth];
}
  • 打印结果就是调用顺序
2015-06-05 19:23:41.159 08-微博-autolayout-xib[1209:325549]
-[SLStatusTableViewController tableView:heightForRowAtIndexPath:]
2015-06-05 19:23:41.159 08-微博-autolayout-xib[1209:325549]
cellForRowAtIndexPath
  • 但是如果实现了tableView:estimatedHeightForRowAtIndexPath:方法的话,调用顺序就会改变
2015-06-05 19:25:22.092 08-微博-autolayout-xib[1237:334971]
-[SLStatusTableViewController tableView:estimatedHeightForRowAtIndexPath:]
2015-06-05 19:25:22.092 08-微博-autolayout-xib[1237:334971]
cellForRowAtIndexPath
2015-06-05 19:25:22.111 08-微博-autolayout-xib[1237:334971]
-[SLStatusTableViewController tableView:heightForRowAtIndexPath:]

自定义非等高CellHeight

  • xib自定义cell(重点)

    • 在模型中增加一个cellHeight属性,用来存放对应cell的高度
    • 在cell的模型属性set方法中调用[self layoutIfNeed]方法强制布局,然后计算出模型的cellheight属性值
    • 在控制器中实现tableView:estimatedHeightForRowAtIndexPath:方法,返回一个估计高度,比如200
    • 在控制器中实现tableView:heightForRowAtIndexPath:方法,返回cell的真实高度(模型中的cellHeight属性)
  • storyboard自定义cell

  • 代码自定义cell(frame)

  • 代码自定义cell(Autolayout)

UILable的宽度问题

  • 问题:代码创建UILable的时候,设置numberOfLines = 0后,没有效果。

  • 解决:在设置模型的代码中,再设置numberOfLines这个属性,在init方法和awakeFromNib中设置都没用。因为那个时候还没有设置UILable的内容,UILable不知道自己需要多高多宽。

  • 如果设置了lable的宽度,文字过多的时候,会报一个错误。

  • 解决:设置lable每一行文字的最大宽度

// 只执行一次此方法
- (void)awakeFromNib
{
    // 设置label每一行文字的最大宽度
    // 为了保证计算出来的数值 跟 真正显示出来的效果 一致
    self.contentLable.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 20;
}

keyboard

键盘弹出来时对视图的处理

  • 监听键盘的状态改变
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameCHange:) name:UIKeyboardWillChangeFrameNotification object:nil];

  • 处理方式1
    • transform
- (void)keyboardFrameCHange:(NSNotification *)notification
{
    CGFloat WH =   [UIScreen mainScreen].bounds.size.height;
    CGRect rect =  [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat time = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

// Y方向位移键盘的值== 键盘的高度
[UIView animateWithDuration:time animations:^{
    self.view.transform = CGAffineTransformMakeTranslation(0, rect.origin.y - WH);
    }];
}
  • 处理方式2
    • 约束
    • 取出最下方的底部控件的 对于 self.view的最底部约束(Vertical Space - View - View)
- (void)keyboardFrameCHange:(NSNotification *)notification
{
    CGFloat WH =   [UIScreen mainScreen].bounds.size.height;
    CGRect rect =  [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat time = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    // 如果等于键盘的y值等于当前的屏幕高度,则表示键盘缩回去了
    // 反之,则说明键盘出来了
    // 可以把下面的代码加入动画中
    if(rect.origin.y != WH)
    {
        self.bottomSpace.constant = rect.size.height;

    }else self.bottomSpace.constant = 0;
    [UIView animateWithDuration:time animations:^{
        [self.view layoutIfNeeded];
    }];
}
原文地址:https://www.cnblogs.com/coderAlin/p/4751899.html