重用自定义TableViewCell

问题描述 投票:0回答:2

我有一个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,但是当我运行代码时,这些单元格为空,我可以看到UIImageViewUILabel为零!

#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中正确填充单元格?

ios objective-c uitableview storyboard
2个回答
0
投票

我知道此问题的两种解决方法。为xib制作单元并注册笔尖。或以编程方式制作UI。

我希望对您有用:https://stackoverflow.com/a/45768693/1678018


-1
投票

您由于未注册自定义表格视图单元而获得空单元格,请使用 [self.numbersTableView registerNib:[UINib nibWithNibName:@"AZGCountryCell" bundle:nil] forCellReuseIdentifier:@"NumbersTableViewCell"];

代替

[self.numbersTableView registerClass:[AZGCountryCell class] forCellReuseIdentifier:@"NumbersTableViewCell"];

© www.soinside.com 2019 - 2024. All rights reserved.