一般使用tableView,只需要讓控制器遵循UITableViewDataSource協(xié)議并成為tableView的數(shù)據(jù)源,然后設(shè)置cell就行了
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
// 設(shè)置數(shù)據(jù)
cell.imageView.image = ...;
cell.textLabel.text = ...;
return cell;
}
這里直接使用的是系統(tǒng)自帶的cell樣式,并設(shè)置了重用標(biāo)識(shí)
但如果想自定義cell,該如何做呢?
一般自定義控件都是重寫(xiě)UIView的initFrame方法,因?yàn)椴还苁钦{(diào)用對(duì)象的init方法還是initWithFrame方法都會(huì)調(diào)用initWithFrame方法。
那么是不是也能通過(guò)重寫(xiě)initFrame方法來(lái)自定義cell呢,我們發(fā)現(xiàn)初始化cell有4種方法,但是能設(shè)置重用標(biāo)識(shí)的下面兩種
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(nullable NSString *)reuseIdentifier
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier
但是第一種已經(jīng)被劃掉了,所以是不建議使用的。這時(shí)我心中就有了疑惑,既然是使用initWithStyle這種方式,那么肯定是需要用系統(tǒng)自帶的樣式(因?yàn)橄到y(tǒng)自帶的樣式中沒(méi)有custom這個(gè)選項(xiàng)),但是我想要用的是我自定義的cell,系統(tǒng)應(yīng)該提供一個(gè)可以使用自定義樣式的方法才對(duì),那我就會(huì)想到用initWithFrame方法來(lái)創(chuàng)建,蘋果為何要將這個(gè)可以順理成章地使用自定義cell的方法劃掉呢?
我按cmd點(diǎn)進(jìn)去查看initWithframe方法的頭文件,發(fā)現(xiàn)這樣一句話
Frame is ignored. The size will be specified by the table view width and row height.
也就是說(shuō)設(shè)置frame會(huì)被忽略,cell的尺寸會(huì)被規(guī)定為tableView的寬度和行高。
當(dāng)然創(chuàng)建cell還有另外更簡(jiǎn)便的方式便是通過(guò)注冊(cè)cell來(lái)簡(jiǎn)化床架cell的過(guò)程,在viewDidLoad中加入
[self.tableView registerClass:[TRStatusCell class] forCellReuseIdentifier:ID];
然后在創(chuàng)建cell的時(shí)候只需要寫(xiě)
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
通過(guò)這種方式創(chuàng)建的時(shí)候,系統(tǒng)也不會(huì)調(diào)用initWithFrame: reuseIdentifier:方法,只會(huì)調(diào)用initWithStyle: reuseIdentifier:方法
一些思考
所以想要自定義cell,重寫(xiě)initWithStyle: reuseIdentifier:方法就行了。但是我想蘋果能不能在style中加一個(gè)像UIButton那樣的custom樣式,
或者提供一個(gè)比如說(shuō)initWithReuseIdentifier:這樣的方法,讓注冊(cè)創(chuàng)建cell的這種方式也只調(diào)用這種方法。讓使用系統(tǒng)自帶樣式的cell和使用自定義的cell有不同的方式,有個(gè)明顯的區(qū)分,這樣能夠統(tǒng)一整個(gè)系統(tǒng)代碼的風(fēng)格是不是更好一些,歡迎大家和我一起討論。