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

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

[OC]TableView使用

[OC]TableView使用

别忘了这俩

[OC]TableView使用

[OC]TableView使用

把label拖到TableViewCell.h里面

[OC]TableView使用

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

[OC]TableView使用

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

[OC]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; }

 运行结果就不贴图了

相关文章:

  • 2021-11-09
  • 2022-12-23
  • 2022-01-13
  • 2021-05-20
  • 2021-07-03
  • 2021-08-06
  • 2021-09-23
  • 2021-12-25
猜你喜欢
  • 2021-07-30
  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2021-06-04
  • 2021-06-11
  • 2021-11-21
相关资源
相似解决方案