UITableView的使用方法和示例

来源:互联网 发布:三k党 知乎 编辑:程序博客网 时间:2024/05/21 22:48

注:本文为原创,转载请注明出处。来自CSDN,作者:Midfar Sun

相信很多人在开发时都需要用到UITableView,包括UITableViewCell的显示,以及对数据增删改查操作。可惜的是苹果官方在这方面的示例很少,而UITableView可以说是使用最复杂的一个控件,很多的坑。这里,我就写了一个MFTableDemo,展示了相关的使用方法,包括Cell的添加、修改、删除、移动。示例程序从这里下载:
https://github.com/midfar/MFTableDemo


下面,我就来对Demo实现的功能做一些讲解,以及开发中要注意的一些问题。

1. TableView的数据显示。
相信很多人都很熟悉了,这里就不多说,直接上代码,关键是实现:

//Cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

//每个Cell的UI,界面显示在Main.StoryBoard的Cell中定义,注意在这里有标注Identifier=Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

//这里返回每一个Cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

//用户选择了Cell需要执行的动作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;


2. 删除Cell。
如果设置了isSupportSingleDelete=YES,那么在列表页面下,从右往左滑动Cell,会出现一个Delete按钮,点击即可删除该Cell。

//必须return YES 才会出现删除按钮
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;

用户点击右上角的Edit按钮后,进入编辑模式,这里通过设置isSupportMutiDelete变量,可以支持多项删除。
mTableView.allowsMultipleSelectionDuringEditing = isSupportMutiDelete;
如果设置为YES,那么需要自己定义一个Delete按钮,在用户点击Cell后记录下来选中项,并在点击Delete按钮后实现相应的删除方法。
注意:移动Cell后会导致记录的indexPath不正确,因此移动后要修改选中的记录。


3. 移动Cell。用户点击右上角的Edit按钮后,进入编辑模式,用户可以对每个Cell进行移动操作。

[mTableView setEditing:!isSelected animated:YES];

//必须return YES 才能移动
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;

//设置可移动的Cell
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;

//用户将cell从src位置拖动到dest位置后,会触发该回调
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;


4. 编辑Cell。用户点击Cell中的文字,将会弹出键盘,可对相关内容进行修改。
点击Next后,如果下一项存在,则会自动跳到下一项。这里要注意TableView的动画问题。


5. 到最后一项后,如果用户继续输入内容,再回车,则会添加新的Cell用于创建新数据。


开发中要注意的问题:
1. 直接对UITableViewCell 设置 showsReorderControl 属性,在部分iOS系统下没效果
2. 在tableView:editingStyleForRowAtIndexPath: 中如果对不同的Cell设置不同的EditingStyle,会导致Cell重用时UI显示问题
3. 在编辑模式下,键盘弹出时,移动Cell后如果不reloadData,会导致Cell重用时UI显示问题
   在键盘弹出时,很多功能的使用会造成UI上的显示问题,开发时要避免相应情况的出现
4. 在键盘弹出时,需要动态调整UITableView的内容区域高度,我这代码中用到了MFKeyboardAvoidingTableView。
5. 为了更好的用户体验,在移动、删除时,尽量不要reloadData,避免没有相关的动画
6. 对于用户的输入,要实时保存下来,避免数据丢失。这里用到了 textField:shouldChangeCharactersInRange:replacementString:



1 0
原创粉丝点击