iOS UITableView的简单使用(一)

2018-11-02  本文已影响0人  feitry

UITableView的使用:
1,在@interface中,声明UITableView的属性控件和数组
代码:

#pragma mark - 表格
@property (nonatomic,strong) UITableView *tableView;
#pragma mark - 数组
@property (nonatomic,strong) NSMutableArray *dataArray;

2,在@implementation中实现,或者叫初始化表格和数组对象,代码:


-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        
        _tableView.dataSource = self;//遵循数据源
        _tableView.delegate = self;//遵循协议
        
    }
    return _tableView;
}
//懒加载
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];//初始化数组
    }
    return _dataArray;
}

3遵循数据源(UITableViewDataSource)和协议(UITableViewDelegate),代码:

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
#pragma mark - 表格
@property (nonatomic,strong) UITableView *tableView;
#pragma mark - 数组
@property (nonatomic,strong) NSMutableArray *dataArray;
@end

4,实现数据源(UITableViewDataSource)和代理(UITableViewDelegate)方法,代码:

//分区、组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
//每个分区的行数、每组的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
//每个单元格的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    /*系统的单元格
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellID"];
    }
    Model *m = self.dataArray[indexPath.row];//取出数组元素
    cell.textLabel.text = [NSString stringWithFormat:@"姓名:%@,年龄:%@",m.name,m.age];
     
     */
//自定义cell,需要注册
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCellID" forIndexPath:indexPath];
    Model *m = self.dataArray[indexPath.row];//取出数组元素
    cell.textLabel.text = [NSString stringWithFormat:@"姓名:%@,年龄:%@",m.name,m.age];

    return cell;
}

注意:使用自定义cell时,注册方法在viewDidLoad中添加,此外,需要在viewDidLoad中将表格添加到主视图。代码:


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];//添加表格到视图
    //添加数组元素
    Model *m0 = [[Model alloc]init];
    m0.name = @"张三";
    m0.age=@"16岁";
    [self.dataArray addObject:m0];
//    [self.dataArray addObject:@"第一组"];
//    [self.dataArray addObject:@"第二组"];
    // Do any additional setup after loading the view, typically from a nib.
    
    //注册cell
    [self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"TableViewCellID"];
}

补充,模型中的代码如下:

@interface Model : NSObject
@property (nonatomic,copy) NSString *name;//姓名
@property (nonatomic,copy) NSString *age;//年龄
@end

Demo地址:

上一篇下一篇

猜你喜欢

热点阅读