我有一个viewController
,其中包含以编程方式创建的tableView
。
@property (strong, nonatomic) UITableView *numbersTableView;
//...
self.numbersTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -100, self.view.frame.size.width-20, 50)];
self.numbersTableView.delegate = self;
self.numbersTableView.dataSource = self;
self.numbersTableView.tag = 1;
self.numbersTableView.layer.cornerRadius = 5;
[self.numbersTableView setBounces:false];
[self.numbersTableView setHidden:true];
[self.numbersTableView registerClass:[AZGCountryCell class] forCellReuseIdentifier:@"NumbersTableViewCell"];
[self.view addSubview:self.numbersTableView];
对于原型单元,我想使用在另一个viewController
中其他地方创建的原型,并在情节提要中对其进行设计。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView.tag == 1) { //tableView == self.numbersTableView
NSString *cellID = @"NumbersTableViewCell";
AZGCountryCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[AZGCountryCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.countryName.text = self.numbersArray[indexPath.row].number;
cell.flagImageView.image = [UIImage imageNamed:self.numbersArray[indexPath.row].country];
return cell;
}
}
并且我的自定义单元格包含一个UIImageView
和一个UILabel
,但是当我运行代码时,这些单元格为空,我可以看到UIImageView
和UILabel
为零!
#import <UIKit/UIKit.h>
@interface AZGCountryCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UIImageView *flagImageView;
@property (strong, nonatomic) IBOutlet UILabel *countryName;
@property (strong, nonatomic) IBOutlet UILabel *countryCode;
@end
#import "AZGCountryCell.h"
@implementation AZGCountryCell
@synthesize flagImageView;
@synthesize countryName;
- (void)awakeFromNib {
[super awakeFromNib];
self.flagImageView.layer.cornerRadius = self.flagImageView.frame.size.width/2;
self.flagImageView.layer.masksToBounds = YES;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
@end
然后我该怎么做才能在numbersTableView
中正确填充单元格?
我知道此问题的两种解决方法。为xib制作单元并注册笔尖。或以编程方式制作UI。
您由于未注册自定义表格视图单元而获得空单元格,请使用
[self.numbersTableView registerNib:[UINib nibWithNibName:@"AZGCountryCell" bundle:nil] forCellReuseIdentifier:@"NumbersTableViewCell"];
代替
[self.numbersTableView registerClass:[AZGCountryCell class] forCellReuseIdentifier:@"NumbersTableViewCell"];