我可以将数据传递给自定义UITableViewCell吗?

时间:2015-01-17 19:13:55

标签: xcode uitableview

我试图将数据传递给自定义UITableViewCell但变量(例如studentId)始终为null。有人可以帮助指出我做错了吗?

CustomCell.h:

#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell { }
@property (strong, nonatomic) NSNumber *studentId;
- (id)initWithStudentId:(NSNumber *)newStudentId;
@end

CustomCell.m:

#import "CustomCell.h"

@interface CustomCell ()
@end

@implementation CustomCell { }

@synthesize studentId = _studentId;

- (id)initWithStudentId:(NSNumber *)newStudentId {
    if (self = [super init]) {
        _studentId = newStudentId;
    }

    return self;
}

StudentTable.m:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *myStudentId = @5;

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"studentCell"];
    if(cell == nil){
        cell = [[CustomCell alloc] initWithStudentId:myStudentId;
    }
    return cell;
}

1 个答案:

答案 0 :(得分:1)

变量未被传递,因为您只是在单元格为零时初始化数据(或者对于这种情况,您可能已经在故事板中定义了原型单元格。)

要解决此问题,只需在if语句的之后执行以下 cell == nil

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     Int myStudentId = @5;

     CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"studentCell"];
     if(cell == nil){
         cell = [[CustomCell alloc] initWithStudentId:[NSNumber numberWithInt:myStudentId]];
     }


     cell.studentId = [NSNumber numberWithInt:myStudentId];


     return cell;
}