现在的位置: 首页 > 综合 > 正文

【iOS开发-58】tableView初识:5个重要方法的使用和2种样式的区别

2017年03月21日 ⁄ 综合 ⁄ 共 2075字 ⁄ 字号 评论关闭

创建一个tableView,直接拖拽放在storyboard里面即可。

(1)先创建一个数据模型类WSCarGroup,在WSCarGroup.h文件中:

#import <Foundation/Foundation.h>

@interface WSCarGroup : NSObject

@property(nonatomic,copy) NSString * title;
@property(nonatomic,copy) NSString * desc;
@property(nonatomic,strong) NSArray *cars;

@end

(2)在ViewController.m中:

——先把数据转成模型,这里没有plist,所以直接手动输入。

先声明一个装模型的数组变量

@property (nonatomic,strong) NSArray *carGroups;

-(NSArray *)carGroups{
    if (_carGroups==nil) {
        WSCarGroup *cg1=[[WSCarGroup alloc]init];
        cg1.title=@"德系汽车";
        cg1.desc=@"质量最精良";
        cg1.cars=@[@"宝马",@"奥迪",@"奔驰"];
        
        WSCarGroup *cg2=[[WSCarGroup alloc]init];
        cg2.title=@"日系汽车";
        cg2.desc=@"很轻很省油";
        cg2.cars=@[@"三菱",@"日产",@"本田",@"三菱",@"日产",@"本田",@"三菱",@"日产",@"本田",@"三菱",@"日产",@"本田"];
        
        _carGroups=@[cg1,cg2];
    }
    return _carGroups;
}

——设置tableView的数据源,和协议类似,充当数据源的要遵守“协议”。此处我们把ViewController当做数据源。所以先遵守:

@interface ViewController ()<UITableViewDataSource>

——然后设置成数据源

- (void)viewDidLoad {
    self.tableView.dataSource=self;
    [super viewDidLoad];
}

——tableView最重要的几个方法

111、设置多少组(如果省略这个方法,则默认是1组)

222、设置每组有多少行

333、设置每行的cell填充什么内容(最重要)

444、设置每组头部标题文字

555、设置妹婿尾部描述文字

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.carGroups.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    WSCarGroup *cg=self.carGroups[section];
    return cg.cars.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //因为要返回UITableViewCell,所以先创建一个,然后赋值,最后返回,即可。
    UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    WSCarGroup *cg=self.carGroups[indexPath.section];
    cell.textLabel.text=cg.cars[indexPath.row];
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    WSCarGroup *cg=self.carGroups[section];
    return cg.title;
}

-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    WSCarGroup *cg=self.carGroups[section];
    return cg.desc;
}

——当然,为了展示方便,隐藏顶部状态栏

-(BOOL)prefersStatusBarHidden{
    return YES;
}

tableView有两种展现形式:plain和grouped。

——plain就是每组之间间隔很小,分组不明显。grouped每组间隔大分组明显。如下:

——plain有头部悬停效果,类似于QQ分组好友的那个组名称在最顶部悬停,直到被下一组顶替。

抱歉!评论已关闭.