我一直在搜索很多,但没有找到与多个自定义行相关的任何有用信息,我需要为我的应用程序创建一个设置 tableView,其中我需要从 xib 文件加载行,例如:
第 1 行 =>> XIB 1。
第 2 行 =>> XIB 2。
第 3 行 =>> XIB 3。
第 4 行 =>> XIB 4。
我现在的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=nil;
//We use CellType1 xib for certain rows
if(indexPath.row==0){
static NSString *CellIdentifier = @"ACell";
cell =(ACell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil){
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"ACell" owner:self options:nil];
cell = (ACell *)[nib objectAtIndex:0];
}
//Custom cell with whatever
//[cell.customLabelA setText:@"myText"]
}
//We use CellType2 xib for other rows
else{
static NSString *CellIdentifier = @"BCell";
cell =(BCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil){
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"BCell" owner:self options:nil];
cell = (BCell *)[nib objectAtIndex:0];
}
//Custom cell with whatever
//[cell.customLabelB setText:@"myText"]
}
return cell;
}
首先,您创建一些自定义 UITableViewCell 类(.h 和 .m),数量与您拥有的 xib 文件一样多:
例如,您可以使用 CellType1 和 CellType2。
CellType1.h 看起来像
#import <UIKit/UIKit.h>
@interface CellType1 : UITableViewCell
@property(nonatomic,strong) IBOutlet UILabel *customLabel;
@end
然后创建 xib 文件,可以使用默认视图类型,但是只需删除自动创建的视图,将其替换为 UITableViewCell,并将类更改为 CellType1。对 CellType2 执行相同操作。
然后在你的 tableViewController 中,像这样编写 cellForRow :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=nil;
//We use CellType1 xib for certain rows
if(indexPath.row==<whatever you want>){
static NSString *CellIdentifier = @"CellType1";
cell =(CellType1*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil){
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"CellType1" owner:self options:nil];
cell = (CellType1 *)[nib objectAtIndex:0];
}
//Custom cell with whatever
[cell.customLabel setText:@"myText"]
}
//We use CellType2 xib for other rows
else{
static NSString *CellIdentifier = @"CellType2";
cell =(CellType2*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil){
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"CellType2" owner:self options:nil];
cell = (CellType2 *)[nib objectAtIndex:0];
}
//Custom cell with whatever
[cell.customLabel setText:@"myText"]
}
return cell;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)