UItableView(继承自UIscrollView)与其相关的协议是
UITableViewDelegate (tableView的一些属性设置)
UITableViewDataSource(tableView的数据来源)
基础使用步骤:1.设置delegate,和DataSource两个代理;
2.实现两个协议当中的方法;
UITableViewDataSource当中的方法:
(1)调用下列方法得知table一共有多少组数据;
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
(2)调用下列方法得知每组有多少行数据;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
(3)调用下列方法得知每一行显示什么内容;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
其实table当中显示每组的内容就是3个部分:组头,每行的cell,组底:
(4)控制组头显示的内容
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
(5)控制组底显示的内容
- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
显示table中的索引,例如通讯录中的(ABCD...Z):
(6)显示索引列的值
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView;
(7)点击索引所显示的内容,即索引定位:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;
cell有个属性selectionStyle,表示点击cell的样式,当其值不为UITableViewCellSelectionStyleNone,即表示cell可点击
(1)当cell可选时,点击cell时,触发的方法:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
可以在该方法中处理数据,刷新数据。
[tableView deselectRowAtIndexPath:indexPath animated:YES]; //如果不调用该方法,则点击cell后,cell一直显示被点击状态。
[self.tabl reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];//诺cell的内容发生改变,则调用该方法刷新cell的数据。
(2)控制每组的组头,组底,以及每行cell的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
(3)滑动cell时,设置出现的按钮样式:
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;//设置按钮样式
- (nullable NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath;//当按钮样式为delete的时候,利用该方法设置按钮名称,如:@“删除”;
当实现了上述两种方法后,点击按钮,会触发UITableViewDataSource当中的方法:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;//可在该方法中设置点击按钮所触发的操作,如:删除某条cell
[tableVie deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
诺没有实现上述两种方法,则可直接实现下面这种方法,在初始化rowAction的时候,可以实现其中的block参数,即点击按钮,回调block:
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath;//设置滑动cell时,出现多少个按钮
Demo地址:https://github.com/liaozhi85/UItableView-UISearchController