自定义表视图单元格
我为我的UITableView创build了一个自定义的UITableView Cell类。 但是,由于某些原因,我无法在单元格中设置值。 就像在userName和userImage这样的值不会显示何时加载表。 这个问题已经持续了几天。 下面是我的代码,为了简单起见,我使用了虚拟值。 如果有人可以请让我知道我做错了,这将不胜感激。
谢谢!
码
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; }
这是我为自定义单元格做的:
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"
来访问标签的文本。
我会为该类添加两个方法:
- (void)setUserName:(NSString *)aUserName { [userNameLabel setText:aUserName]; // mark view as dirty [self setNeedsDisplay]; }
为userImage做同样的事情。
然后通过调用:
[cell setUserName:@"Foo"];
你可以试试这个 改变你的代码行
cell.userName=@"Adam Scott"; cell.userImage=[UIImage imageNamed:@"adam.png"];
对此
cell.userName.text=@"Adam Scott"; cell.userImage.image=[UIImage imageNamed:@"adam.png"];
试试这个
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; }