如何讓tableView展現數據

  • 設置數據源對象
self.tableView.dataSource = self;
  • 數據源對象要遵照協議
@interface ViewController () <UITableViewDataSource>

@end
  • 實現數據源方法
// 多少組數據
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

// 每一組有多少行數據
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

// 每一行顯示什麼內容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

// 每一組的頭部
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;

// 每一組的尾部
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section

tableView的常見設置

// 設置每一行cell的高度
self.tableView.rowHeight = 100;

// 設置每一組頭部的高度
self.tableView.sectionHeaderHeight = 50;

// 設置每一組尾部的高度
self.tableView.sectionFooterHeight = 50;

// 設置分割線顏色
self.tableView.separatorColor = [UIColor redColor];
// 設置分割線樣式
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
// 設置表頭控件
self.tableView.tableHeaderView = [[UISwitch alloc] init];
// 設置表尾控件
self.tableView.tableFooterView = [UIButton buttonWithType:UIButtonTypeContactAdd];

// 設置右邊索引文字的顏色
self.tableView.sectionIndexColor = [UIColor redColor];
// 設置右邊索引文字的背景色
self.tableView.sectionIndexBackgroundColor = [UIColor blackColor];

tableViewCell的常見設置

// 設置右邊的指示樣式
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

// 設置右邊的指示控件
cell.accessoryView = [[UISwitch alloc] init];

// 設置cell的選中樣式
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// backgroundView優先級 > backgroundColor

// 設置背景色
cell.backgroundColor = [UIColor redColor];

// 設置背景view
UIView *bg = [[UIView alloc] init];
bg.backgroundColor = [UIColor blueColor];
cell.backgroundView = bg;

// 設置選中的背景view
UIView *selectedBg = [[UIView alloc] init];
selectedBg.backgroundColor = [UIColor purpleColor];
cell.selectedBackgroundView = selectedBg;

cell的循環利用

  • 傳統的寫法
/**
* 每當有一個cell要進入視野範圍內,就會調用一次
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"wine";

// 1.先去緩存池中查找可循環利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

// 2.若是緩存池中沒有可循環利用的cell
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}

// 3.設置數據
cell.textLabel.text = [NSString stringWithFormat:@"%zd行的數據", indexPath.row];

return cell;
}
  • 新的寫法(註冊cell)
NSString *ID = @"wine";

- (void)viewDidLoad {
[super viewDidLoad];

// 註冊某個重用標識 對應的 Cell類型
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1.先去緩存池中查找可循環利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

// 2.設置數據
cell.textLabel.text = [NSString stringWithFormat:@"%zd行的數據", indexPath.row];

return cell;
}
相關文章
相關標籤/搜索