OC-自定義Cell
阿新 • • 發佈:2019-02-02
1.UITableViewCell的組成
內容檢視
系統版
….
自定義:
1.建立要顯示的控制元件
2.將建立好的控制元件以子檢視的形式,新增到cell.contentView中即可
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
if (cell == nil ) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
}
//從cell中獲取label
UILabel *label = [cell.contentView viewWithTag:100];
//如果沒有取出 建立一個新增到 cell.contentView 上
if(label == nil) {
label = [[UILabel alloc]initWithFrame:CGRectMake(0 , 0, tableView.frame.size.width, 60)];
label.tag = 100;
label.textAlignment = NSTextAlignmentCenter;
label.font = [UIFont systemFontOfSize:32];
//將label新增到cell.contentView 上
[cell.contentView addSubview:label];
}
label.text = [NSString stringWithFormat:@"第%ld行" ,indexPath.row];
//第一行的輔助檢視是個開關控制元件
if(indexPath.row == 1) {
UISwitch *mySwitch = [[UISwitch alloc]init];
[mySwitch addTarget:self action:@selector(clickSwitch:) forControlEvents:UIControlEventValueChanged];
//將控制元件賦值給cell.accessoryView
cell.accessoryView = mySwitch;
}else {
cell.accessoryView = nil;
}
return cell;
}
//通過屬性設定行高
self.tableView.rowHeight = 60;
//cell不設定高度的話 預設高度44 如果希望不是44 可以自己設定
//通過代理方法設定 也可以 通過屬性設定
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// return 60;
//}
輔助檢視
系統版
….
自定義
1.建立要顯示的控制元件
2.將建立好的控制元件賦值給cell.accessoryView即可
2.單元格的重用
重用方式一:
核心:如果沒有取出,自己建立
原理:系統會將那麼超出螢幕,看不見的單元格物件回到到tableView的一個佇列中儲存,在需要一個cell物件先嚐試從佇列中取,看有沒有已經回收的cell,如果有把這個cell從佇列中取出繼續使用,如果沒有取出我們就建立新的cell
重用方式二:
核心:如果沒有取出,系統自動建立
原理:在開始的時候向系統註冊一個cell型別的樣式,系統會將那麼超出螢幕,看不見的單元格物件回到到tableView的一個佇列中儲存,在需要一個cell物件先嚐試從佇列中取,看有沒有已經回收的cell,如果有把這個cell從佇列中取出繼續使用,如果沒有系統會根據我們之前註冊的樣式幫我們建立一個cell使用
- (void)viewDidLoad {
[super viewDidLoad];
//向tableview中註冊一個 cell型別 的樣式
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellID"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//重用方式二 如果沒有取出 tableView會根據之前註冊的幫我們建立一個cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
cell.textLabel.text = @"這是一個單元格";
return cell;
}
3.表格結合各種資料模型的顯示
【前提:表格的行數是不定,也叫動態表格】
1.將陣列顯示到表格中
2.將物件陣列顯示到表格中
cell.textLabel.text = self.datas[indexPath.row];