簡體   English   中英

CustomCell沒有反映在UITableView中

[英]CustomCell is not reflected in UITableView

我想在UITableView中使用CustomCell。
但是在下面的代碼中,customCell沒有反映出來。

ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    arr = [NSArray arrayWithObjects:@"aaa", @"bbb", @"ccc", @"ddd", @"eee", @"fff", nil];
    myTableView = [[UITableView alloc]initWithFrame:CGRectMake(20, 130, 280, 220)];
    [myTableView registerClass:[CustomCell class] forCellReuseIdentifier:@"Cell"];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"Cell";
    CustomCell* cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.customLabel.text = [arr objectAtIndex:indexPath.row];
    return cell;
}

CustomCell.m

- (id)init{
    self = [super init];
    if (self){
        self.backgroundColor = [UIColor redColor];
        //But in ViewController, cell is not red.
    }
    return self;
}

如何修復以輸出customCell?

cellForRowAtIndexPath ,將調用initWithStyle:reuseIdentifier:通過以下代碼顯示您在CustomCell.m中以編程方式在CustomCell.m中創建的自定義單元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"Cell";
    CustomCell* cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {

   This Line---> cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];  

}
    cell.customLabel.text = [arr objectAtIndex:indexPath.row];
    return cell;
}

因此,在CustomCell.m文件中,您需要實現initWithStyle:reuseIdentifier:和NOT -init

CustomCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
        if (self) {
            // configure control(s)
            self.backgroundColor = [UIColor redColor];
        }
        return self;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM