我可以将数据传递给自定义 UITableViewCell 吗?
Can I pass data to a custom UITableViewCell?
我正在尝试将数据传递到自定义 UITableViewCell,但变量(例如 studentId)始终为空。谁能帮忙指出我做错了什么?
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;
}
变量没有被传递,因为你只是在单元格为 nil 时初始化数据(或者对于这种情况,你可能已经在故事板中定义了原型单元格)。
要解决此问题,只需在 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;
}
我正在尝试将数据传递到自定义 UITableViewCell,但变量(例如 studentId)始终为空。谁能帮忙指出我做错了什么?
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;
}
变量没有被传递,因为你只是在单元格为 nil 时初始化数据(或者对于这种情况,你可能已经在故事板中定义了原型单元格)。
要解决此问题,只需在 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;
}