初次使用xib創建UITableviewCell的時候,我都是一個xib文件里,只創建一個Cell,在實際業務中,往往都是一個列表中需要用到多個不同的Cell樣式,這就需要創建N個.h .m .xib文件。而且這些.m中的實現還差不多。
后來發現,一個.xib文件中可以創建多個Cell,如圖:
多個Cell
這樣感覺方便多了。
具體實現:
第一步創建
先和普通創建xibCell一樣,在xib中選中左邊那個Cell,copy(command + c),然后paste(command + v).xib中就多個Cell了,O(∩_∩)O~~
多個Cell
第二步設置Identifier和代碼使用
在代碼中創建Cell時
if (!cell) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"TempTableViewCell"owner:self options:nil] firstObject];
}
TempTableViewCell是你的xib文件名,firstObject是第一個Cell,按順序排的。
第二個怎么辦??
cell = [[[NSBundle mainBundle] loadNibNamed:@"TempTableViewCell"owner:self options:nil]objectAtIndex:2];
再多依次類推哈。(提示:如果在Cell中添加手勢的話,loadNibNamed: 這個返回的數組中會比Cell多哦,大家注意)
設置每個Cell的identifier,(identifier 隨意起的,我的規律就是類名+第幾,不要重復就行)如圖:
設置每個Cell的identifier
這樣在重用隊列中重復使用Cell的時候,能找到正確的Cell,
TempTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TempTableViewCellFirst"];
可以根據indexPath設置不同的identifier。
可以把創建Cell的過程放在Cell.m中,做成類方法,這樣不至于VC中的代碼過多。
cell.h中:
@interface TempTableViewCell : UITableViewCell
/**
* @author god~long, 16-04-03 15:04:19
*
* 初始化Cell的方法
*
* @param tableView 對應的TableView
* @param indexPath 對應的indexPath
*
* @return TempTableViewCell
*/
+ (instancetype)tempTableViewCellWith:(UITableView *)tableView
indexPath:(NSIndexPath *)indexPath;
@end
cell.m中:
+ (instancetype)tempTableViewCellWith:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
NSString *identifier =@"";//對應xib中設置的identifier
NSInteger index =0; //xib中第幾個Cell
switch (indexPath.row) {
case0:
identifier = @"TempTableViewCellFirst";
index = 0;
break;
case1:
identifier = @"TempTableViewCellSecond";
index = 1;
break;
case2:
identifier = @"TempTableViewCellThird";
index = 2;
break;
default:
break;
}
TempTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"TempTableViewCell" owner:self options:nil] objectAtIndex:index];
}
return cell;
}
這樣VC中:
- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath {
TempTableViewCell *cell = [TempTableViewCell tempTableViewCellWith:tableView indexPath:indexPath];
return cell;
}
是不是很方便呢。
設置屬性
快捷設置xib屬性:
1. 在.h或者.m中先寫好屬性,如圖:
設置屬性
2. 在xib中就可以拖拽連接屬性了,如圖:
PRoperty.gif
重點:關聯屬性的時候,你想關聯那個Cell上的屬性,需要先點擊左邊Cell列表,選中該Cell,然后再拖線關聯上面的控件。
設置好屬性,下面就是使用了,
配置Cell
/**
* @author god~long, 16-04-03 16:04:04
*
* 配置TempCell的方法
*
* @param indexPath 對應TableView的indexPath
*/
- (void)configTempCellWith:(NSIndexPath *)indexPath;
.m中:
- (void)configTempCellWith:(NSIndexPath *)indexPath {
switch (indexPath.row) {
case0: {
_label1.text = @"我是Label1";
_customImageView.image = [UIImage imageNamed:@"8"];
break;
}
case1: {
_label2.text = @"我是Label2";
[_customButton setTitle:@"我是button" forState:UIControlStateNormal];
break;
}
case2: {
_label1.text = @"我是第三個Cell的Label1";
_label2.text = @"我是第三個Cell的Label2";
break;
}
default:
break;
}
}
重點:每個Cell設置鏈接的屬性都是單獨處理的,沒連,在用的時候即使你用了,也設置不了。
運行效果:
運行效果
dome地址:點我點我
新聞熱點
疑難解答