在咱們複用cell時,若是每一個cell的佈局不一樣,如實現如下的佈局:ide
咱們接下來用Xib文件來進行實現佈局
1.建立TableViewCell文件,在Xib文件中生成6個Cell,並設置每一個Cell的identifier,爲了方便起見,我這裏將其設置爲數字0~5spa
2.在ViewController.m中建立Cellcode
TableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:(nonnull NSString *)]; if (cell==nil) { cell=[[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil] objectAtIndex:(NSUInteger)]; } return cell;
這幾行代碼是正常複用cell的流程,能夠看到,identifier後面接當前Cell的識別碼,index後面要加當前Cell所在位置。it
例如:第一個Cell就是io
TableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"0"]; if (cell==nil) { cell=[[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil] firstObject]; }
第二個Cell是table
TableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"1"]; if (cell==nil) { cell=[[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil] objectAtIndex:1]; }
因此在上面加一個判斷語句,肯定當前Cell的信息object
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath{ NSString*identifier=0; NSInteger index=0; //判斷在第幾組 if (indexPath.section==0) { switch (indexPath.row) { case 0: identifier=@"0"; index=0; break; case 1: identifier=@"1"; index=1; break; case 2: identifier=@"2"; index=2; break; default: break; } }else{ switch (indexPath.row) { case 0: identifier=@"3"; index=3; break; case 1: identifier=@"4"; index=4; break; case 2: identifier=@"5"; index=5; break; default: break; } } TableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:identifier]; if (cell==nil) { cell=[[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil] objectAtIndex:index]; } return cell; }
3.能夠把建立Cell的過程,在Cell.m文件中進行,以避免ViewController中代碼過多queue
TableViewCell.him
+(instancetype)setupCellWith:(UITableView*)tableView AtIndexPath:(NSIndexPath *)indexPath;
TableViewCell.m
+(instancetype)setupCellWith:(UITableView*)tableView AtIndexPath:(NSIndexPath *)indexPath{ NSString*identifier=0; NSInteger index=0; if (indexPath.section==0) { switch (indexPath.row) { case 0: identifier=@"0"; index=0; break; case 1: identifier=@"1"; index=1; break; case 2: identifier=@"2"; index=2; break; default: break; } }else{ switch (indexPath.row) { case 0: identifier=@"3"; index=3; break; case 1: identifier=@"4"; index=4; break; case 2: identifier=@"5"; index=5; break; default: break; } } TableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:identifier]; if (cell==nil) { cell=[[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil] objectAtIndex:index]; } return cell; }
ViewController.m文件中
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath{ TableViewCell*cell=[TableViewCell setupCellWith:tableView AtIndexPath:indexPath]; return cell; }
4.把控件拖到Cell中
這樣咱們的佈局就完成了ಠ౪ಠ