iOS开发中经常会用到UITableView,我们平时使用的软件中到处都可以看到它,比如微信、QQ、微博等软件基本上随处都是UITableView。最主要到还有iOS设置。
一 基本介绍
UITableView有两种Style:UITableViewStylePlain和UITableViewStyleGrouped。从名字上可以看出:一个是普通样式的,另一个是分组样式的。具体上怎样,可以看一下下面的图片。
普通样式(不分组) 分组样式:
UITableView只有行没有列,每一行都是一个UITableViewCell,如果我们查看UITableViewCell的声明文件可以发现在内部有一个UIView控件(contentView,作为其他元素的父控件)、两个UILable控件(textLabel detailTextLabel)、一个UIImage控件(imageView),分别用于容器、显示内容、详情和图片。这些控件并不一定要全部显示,可以根据需要设置。
typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
UITableViewCellStyleDefault, // Simple cell with text label and optional image view (behavior of UITableViewCell in iPhoneOS 2.x)
UITableViewCellStyleValue1, // Left aligned label on left and right aligned label on right with blue text (Used in Settings)
UITableViewCellStyleValue2, // Right aligned label on left with blue text and left aligned label on right (Used in Phone/Contacts)
UITableViewCellStyleSubtitle // Left aligned label on top and left aligned label on bottom with gray text (Used in iPod).
};
这是UITalbeViewCell的四种style。
二 数据源
UITableView需要一个数据源(dataSource)来显示数据,UITableView会向数据源查询一共有多少行数据以及每一行显示什么数据等。没有设置数据源的UITableView只是个空壳。凡是遵守UITableViewDataSource协议的OC对象,都可以是UITableView的数据源。
首先将UITableView对数据源和View controller相连。如图所示:
并且让这个ViewController这个类实现UITableViewDataSource协议。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
@end
先看一下UITableViewDataSource协议:
@protocol UITableViewDataSource<NSObject>
@required //必须要实现的
第section分区一共有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
//创建第section分区第row行的UITableViewCell对象(indexPath包含了section和row)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
@optional //可选择实现的
// 一共有多少个分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
//第section分区的头部标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
//第section分区的底部标题
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
//某一行是否可以编辑(删除)
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
//某一行是否可以移动来进行重新排序
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
UITableView右边的索引栏的内容
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;
这些只是UITableView的显示上面的设置,如果要做一些操作仅这些是不够的。。。
三 代理(delegate)
通常都要为UITableView设置代理对象(delegate),以便在UITableView触发一下事件时做出相应的处理,比如选中了某一行。凡是遵守了UITableViewDelegate协议的OC对象,都可以是UITableView的代理对象。一般会让控制器充当UITableView的dataSource和delegate。
同样需要将UITableView的delegate与UIViewController关联起来。
看一些UITableViewDelegate协议的一些常用方法。