免费开源的iOS开发学习平台

UITableView详解:1-基本介绍

表视图UITableView是iOS开发中最重要的控件(不是之一),99.99%的App都会用到表视图。它之所以使用广泛,也是因为其强大的定制能力,当然学习起来也需要花费一些时间和精力。表视图主要用于呈现一个滚动的选择列表,在使用过程中主要有三个步骤:初始化、数据源的设置以及委托代理方法的实现。

UITableView简介

在实际开发中,我们会看到许多地方都用到了UITableView,如苹果系统中的设置、QQ、微信等。

在UITableView中数据只有行的概念,并没有列的概念,因为在手机中显示多列是不利于操作的。在UIKit框架中,UITableView的继承关系如下图所示。

UITableView样式

UITableView有两种样式:平铺(UITableViewStylePlain)和分组(UITableViewStyleGrouped)。这两者本质区别不大,在没有特别设置的情况下,UITableViewStyleGrouped样式会默认留出header和footer的位置,也就是分组样式。

  • UITableViewStylePlain 普通样式:

  • UITableViewStyleGrouped 分组样式:

UITableView的属性

UITableView类中定义了非常多的属性和方法,也正因为如此,UITableView的功能非常强大。这里只对UITableView的常用属性和方法做一个简单介绍,在后面的文章中会详细讲解。

  • 获取表视图的样式
@property (nonatomic, readonly) UITableViewStyle style;
  • UITableView的数据源对象与代理对象,需要遵守UITableViewDataSource协议与UITableViewDelegate协议
@property (nonatomic, weak, nullable) id <UITableViewDataSource> dataSource;
@property (nonatomic, weak, nullable) id <UITableViewDelegate> delegate;
  • 单元格的行高
@property (nonatomic) CGFloat rowHeight;
  • 段section的header高度与footer高度
@property (nonatomic) CGFloat sectionHeaderHeight;
@property (nonatomic) CGFloat sectionFooterHeight;
  • 整体表视图的顶部视图与底部视图
@property (nonatomic, strong, nullable) UIView *tableHeaderView;
@property (nonatomic, strong, nullable) UIView *tableFooterView;
  • 表索引的样式设置
//索引表的字母的颜色
@property (nonatomic, strong, nullable) UIColor *sectionIndexColor;
//索引栏的背景颜色
@property (nonatomic, strong, nullable) UIColor *sectionIndexBackgroundColor; 
  • 分割线的样式设置
//设置分割线样式
@property (nonatomic) UITableViewCellSeparatorStyle separatorStyle;
//定义分割线颜色
@property (nonatomic, strong, nullable) UIColor *separatorColor;