表格视图

1. 实现UITableViewDataSource协议

2. 实现协议规定的重要方法

// 通知表格视图要装载的区段数(可选)

 numberOfSectionsInTableView:

// 告诉表格视图控制器每个区段应该装载多少单元格或者行数(强制)

tableView:numberOfRowsInSection:

// 返回一个UITableViewCell类的实例,该实例为数据行(强制)

tableView:cellForRowAtIndexPath:

3. 将表格视图数据源指向视图

self.myTableView.dataSource = self;

完整代码如下:

#import "ViewController.h"

static NSString *TableViewCellIdentifier = @"MyCells";

@interface ViewController () <UITableViewDataSource>

@property (nonatomic, strong) UITableView *myTableView;

@end

@implementation ViewController

// 显示3个区段
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{ 
    if ([tableView isEqual:self.myTableView])
    {
        return 3;
    }
    
    return 0;   
}

//  每个区段要显示多少行   
- (NSInteger)tableView:(UITableView *)tableView
                        numberOfRowsInSection:(NSInteger)section
 {   
    if ([tableView isEqual:self.myTableView])
    {
        switch (section)
        {
            // 第1段有3行
            case 0:
            {
                return 3;
                break;
            }
            // 第2段有5行
            case 1:
            {
                return 5;
                break;
            }
            // 第3段有8行
            case 2:
            {
                return 8;
                break;
            }
        }
    }
    
    return 0; 
}

// 为表格视图没行的label显示区段号和该行在本区段内的行号
- (UITableViewCell *)tableView:(UITableView *)tableView
                    cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if ([tableView isEqual:self.myTableView])
    {      
        cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier
                  forIndexPath:indexPath];
        
        cell.textLabel.text = [NSString stringWithFormat:
                                 @"Section %ld, Cell %ld",
                                 (long)indexPath.section,
                                 (long)indexPath.row];        
    }
    
    return cell;    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.myTableView =
    [[UITableView alloc] initWithFrame:self.view.bounds
                                 style:UITableViewStylePlain];
    
    [self.myTableView registerClass:[UITableViewCell class]
             forCellReuseIdentifier:TableViewCellIdentifier];
    
    // 将表格视图数据源指向视图
    self.myTableView.dataSource = self;
    
    /* Make sure our table view resizes correctly */
    self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    [self.view addSubview:self.myTableView];  
}

@end
原文地址:https://www.cnblogs.com/davidgu/p/5056251.html