Monday, 28 October 2019

Reuse custom TableViewCell

I have a viewController that contains a programmatically created 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];

For the prototype cell I want to use a prototype that I created somewhere else in another viewController and I designed It in storyboard.

- (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;
    }
}

And my custom cell contains one UIImageView and one UILabel but when I run the code the cells are empty and I can see the UIImageView and UILabel are nil!

#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

Then what should I do to have properly filled cells in my numbersTableView?



from Reuse custom TableViewCell

No comments:

Post a Comment