[OC]TableView使用

新建一个OC项目,因为这是个简单demo,创建tableView的代码就写在ViewController.m里了。

新建一个TableViewCell类,属于UITableViewCell,别忘了xib。

别忘了这俩

把label拖到TableViewCell.h里面

可以开始添加TableView了,在ViewController.m导入TableViewCell.h

实例化一个UITableView的对象_tableView,加上代理和数据源:

初始化一个数组

NSArray *arr = @[@"a",@"b",@"c"];

 写一个创建tableView的方法

-(void)creatTableView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

在viewDidLoad里调用这个方法

[self creatTableView];

 下面实现tableView的delegate和datasource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return array.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48;
} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellID = @"TableViewCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; if (cell==nil) {
        cell=[[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:self options:nil]lastObject];
    } cell.textLabel.text = arr[indexPath.row]; return cell; }

 运行结果就不贴图了

posted @ 2016-04-18 12:23  ybw123321  阅读(773)  评论(0编辑  收藏  举报