我为我的UITableView创建了一个自定义的UITableView Cell类。但是,由于某种原因,我无法在单元格内设置值。如在userName和userImage之类的值中,在加载表时不显示。这个问题已经持续了几天。下面是我的代码,为简单起见我使用了虚拟值。如果有人可以请让我知道我做错了什么,我们将不胜感激。
谢谢!
CODE
CustomCell.h
@interface CustomCell : UITableViewCell
{
IBOutlet UILabel *userName;
IBOutlet UIImageView *userImage;
}
@property(strong,nonatomic) IBOutlet UILabel *userName;
@property(strong,nonatomic) IBOutlet UIImageView *userImage;
@end
CustomCell.m
#import "CustomCell.h"
@interface CustomCell ()
@end
@implementation CustomCell
@synthesize userName;
@synthesize userImage;
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
// Custom initialization
NSArray *nibArray= [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
self= [nibArray objectAtIndex:0];
}
return self;
}
-(void) setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
@end
ViewController.m (具有调用自定义单元格的UITableView的类)
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";
CustomCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.userName=@"Adam Scott";
cell.userImage=[UIImage imageNamed:@"adam.png"];
return cell;
}
答案 0 :(得分:1)
以下是我为自定义单元格所做的事情:
ReceiverCell *receiverCell = (ReceiverCell *)[tableView dequeueReusableCellWithIdentifier:@"receiverCellIdentifier"];
if (receiverCell == nil) {
receiverCell = [[ReceiverCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"receiverCellIdentifier"];
}
receiverCell.receiverLabel.text=@"The Text";
假设您在IB中连接了所有内容,我认为您需要使用cell.labelName.text=@"Adam Scott"
访问标签的文本。
答案 1 :(得分:1)
我会在该类中添加两个方法:
- (void)setUserName:(NSString *)aUserName {
[userNameLabel setText:aUserName];
// mark view as dirty
[self setNeedsDisplay];
}
对userImage执行相同的操作。
然后通过调用
来设置它[cell setUserName:@"Foo"];
答案 2 :(得分:1)
你可以试试这个。更改你的代码行
cell.userName=@"Adam Scott";
cell.userImage=[UIImage imageNamed:@"adam.png"];
到这个
cell.userName.text=@"Adam Scott";
cell.userImage.image=[UIImage imageNamed:@"adam.png"];
答案 3 :(得分:1)
试试这个
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
if (cell == nil) {
NSArray *top = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id t in top) {
if ([t isKindOfClass:[UITableViewCell class]]) {
cell =(CustomCell*)t;
break;
}
}
}
cell.username.text = @"blabla";
cell.userImage.image = [UIImage imageNamed:@"avatar.png"];
return cell;
}