Reputation: 18491
I'm just trying to test out the custom cell by have all the cells in the table say "Hi", but it won't work... the cells are all blank. It seems that the TheCell class is called before I can set the label text... I don't know how else to do it.
TheCell.h
#import <UIKit/UIKit.h>
@interface TheCell : UITableViewCell
@property (nonatomic, strong) IBOutlet UILabel *arrivalLabel;
@end
TheCell.m
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.arrivalLabel.frame = CGRectMake(0, 0, 320, 30);
[self.contentView addSubview:self.arrivalLabel];
}
return self;
}
TableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"anIdentifier";
TheCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[TheCell alloc] init];
cell.arrivalLabel.text = @"hi";
return cell;
}
Upvotes: 1
Views: 219
Reputation: 318774
You have a few issues. You are calling the init
method of your cell class. You should be calling the initWithStyle:reuseIdentifier:
method instead.
You should also only allocate the cell if the call to dequeue...
returns nil
.
Then you need to make sure that your cell's initWithStyle:reuseIdentifier:
method is creating the label instance for the arrivalLabel
property.
TheCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[TheCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.arrivalLabel.text = @"hi";
The other big problem is in your cell's initWithStyle:reuseIdentifier:
method. You never create the label.
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_arrivalLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
[self.contentView addSubview:_arrivalLabel];
}
return self;
}
Upvotes: 3
Reputation:
This is not correct:
TheCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[TheCell alloc] init];
You have to do something like:
TheCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[TheCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Upvotes: 2