原文網址:http://www.kancloud.cn/digest/ios-1/107420
上一節中,我們定義的cell比較單一,只是單調的輸入文本和插入圖片,但是在實際開發中,有的cell上面有按鈕,有的cell上面有滑動控件,有的cell上面有開關選項等等,具體參加下面2個圖的對比:
?? ???? ?
@我們可以通過2種方式來實現自定義,一是利用系統的UITableViewCell(但不推薦,因為開發效率不高),舉例:還是在這個關鍵方法中
(UITableViewCell)tableView:(UITableView)tableView cellForRowAtIndexPath:(NSIndexPath)indexPath{static NSString cellIdentifier? = @"cell"; ? ??UITableViewCell cell = [tableViewdequeueReusableCellWithIdentifier:cellIdentifier]; ? ??if(!cell) { ? ? ? ? cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellIdentifier];
? ? ?// 首先,各種按鈕控件的初始化,一定要放在這個if語句里面,如果放在這個大括號外面,cell被執行n次,那么一個cell上面就會被添加n個控件
? ? ?// 其次,你在這個括號里面自定義初始化控件后,如果你想給每一個cell的控件顯示不同的內容和效果,你在括號外面是取不到對象的,只有通過設置它們繼承UIView的屬性tag來標識,我們可以想一想,如果控件一多或者別人來接受你的項目,你自己定義了很多的tag,這樣合作的效率不高,所以主要推薦第二種
}return cell;
}
@二是,創建UITableViewCell子類,在contentView上實現自定義效果(cell上的所有內容都是顯示在cell的屬性contentView上),這里也是寫這個方法
#import <UIKit/UIKit.h>@interface HMTAssistCell : UITableViewCell @property (nonatomic) UILabel * label; @property (nonatomic) UIButton * button; @end - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { _button = [UIButton buttonWithType:UIButtonTypeSystem]; _button.backgroundColor = [UIColor redColor]; _button.frame = CGRectMake(150, 60, 50, 100); [_button setTitle:@"油條" forState:UIControlStateNormal]; [self.contentView addSubview:_button]; _label = [[UILabel alloc]initWithFrame:CGRectMake(10, 30, 100, 100)]; _label.backgroundColor = [UIColor greenColor]; [self.contentView addSubview:_label]; } return self; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // 依舊設置重用標識 static NSString * cellIdentifier = @"cell"; // 這里用我們新建的UITableViewCell的子類進行cell重用聲明 HMTAssistCell * cell = (HMTAssistCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; // 如果沒有,則創建 if (!cell) { cell = [[HMTAssistCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } // 因為_label是類HMTAssistCell中的屬性,所以就能很方便的取出來進行賦值 cell.label.text = [NSString stringWithFormat:@"%d",indexPath.row]; return cell; }