在前面, 我们把UIPickerView基本上已经是演练完了, 剩下的就是靠大家去熟练的掌握了, 现在让我们来看看另外一个高级控件, 也是我们经常会使用到的UI控件, UITableView, 在写代码之前, 我们首先来看看UITableView的一些须知信息:
1.UITableView需要一个dataSource(数据源)来显示数据, UITableView会向dataSource查询一共又多少行数据以及每一行显示什么数据等等. 没有设置dataSource的UITableView只是一个空空当当的View.
PS:凡事遵守UITableViewDataSource协议的OC对象, 都可以是UITableView的数据源, 这是毋庸置疑的.
2.通常都要为UITableView设置代理Delegate(代理对象), 以便在UITableView触发事件时做出相应的处理, 比如选中了某一行, 需要做什么, 显示什么等等.
PS:凡事遵守了UITableViewDelegate协议的OC对象, 都可以是UITableView的代理对象.
一般情况下, 会让Controller从当UITableView的dataSource和Dlegate.
现在让我们一起来看看到底什么是UITableView.
1.在.h文件中遵守UITableViewDataSource协议
@interface ViewController : UIViewController <UITableViewDataSource> @end
2.在.m文件中声明全局变量
@interface ViewController () @property (strong, nonatomic) NSArray *writer1; @property (strong, nonatomic) NSArray *writer2; @end
PS: 之前我说过在.m文件中也是可以定义属性的.
3.添加UITableView
- (void)myTableView
{
// 这个style分别有两种, 一种是分组模式, 一种是平面模式
// Plain模式是平面模式
// Grouped是分组模式
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 28, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
[tableView setDataSource:self];
[self.view addSubview:tableView];
}
4.初始化数据
- (void)myArray
{
self.writer1 = @[@"完美世界", @"遮天", @"神墓"];
self.writer2 = @[@"天火大道", @"绝世唐门", @"神印王座", @"琴帝"];
}
5.实现UITableViewDataSource的方法
#pragma mark 分组 Sections表示表格的组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
#pragma mark 每个分组中显示的数据量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
{
return self.writer1.count;
} else {
return self.writer2.count;
}
}
#pragma mark 每个分组中显示的数据内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *tableViewCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
NSString *citysName = nil;
if (indexPath.section == 0) {
citysName = _writer1[indexPath.row];
} else {
citysName = _writer2[indexPath.row];
}
[tableViewCell.textLabel setText:citysName];
return tableViewCell;
}
6.添加UITableView的标题和页尾描述方法
#pragma mark 分组的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return section == 0 ? @"辰东" : @"唐家三少";
}
#pragma mark 分组描述
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
if (section == 0) {
return @"辰东小说作品集";
} else {
return @"唐家三少小说作品集";
}
}
7.在viewDidLoad中实现所有方法以及初始
- (void)viewDidLoad {
[super viewDidLoad];
[self myArray];
[self myTableView];
}
UITableViewStyleGrouped最终的效果:
UITableViewStylePlain最终的效果:
好了, 这次我们就讲到这里, 下次我们继续~~~