UITableViewCell无法从NIB正确显示/重用

时间:2010-06-08 16:34:47

标签: iphone objective-c cocoa-touch uitableview interface-builder

我已经从NIB创建了一个自定义UITableViewCell。当没有设置rowHeight时,所有内容都会出现(虽然一切都被压扁了)。我不确定我是否正在重复使用并正确创建单元格:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *MyIdentifier = @"ARCell";
    ARObject *myARObject;
    myARObject = [items objectAtIndex:indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"ARCell" owner:self options:nil];
        cell = arCell;
        self.arCell = nil;
    }

    UILabel *label;
    label = (UILabel *)[cell viewWithTag:0];
    label.text = [NSString stringWithFormat:@"%@", myARObject.username];

    label = (UILabel *)[cell viewWithTag:1];
    label.text = [NSString stringWithFormat:@"%@", myARObject.created_at];

    label = (UILabel *)[cell viewWithTag:2];
    label.text = [NSString stringWithFormat:@"%@", myARObject.articleTitle];

    label = (UILabel *)[cell viewWithTag:3];
    label.text = [NSString stringWithFormat:@"%@", myARObject.intro_text];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tblView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{   CGFloat rowHeight = 105;
    return rowHeight;
}

问题:

  1. 设置rowHeight时,并非所有标签都出现。如果未设置rowHeight,则标签会被压扁
  2. 未设置rowHeight时,选择项目会显示所有标签

2 个答案:

答案 0 :(得分:0)

删除else子句

答案 1 :(得分:0)

您调用loadNibNamed,但不将结果存储在任何位置!无法理解你的代码为什么会起作用......无论如何,写盲我会尝试这样的事情:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"ARCell";
    ARObject *myARObject = [items objectAtIndex:indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ARCell" owner:self options:nil];
        cell = (UITableViewCell *)[nib objectAtIndex:0];
   }

    UILabel *label;
    label = (UILabel *)[cell viewWithTag:0];
    label.text = [NSString stringWithFormat:@"%@", myARObject.username];

    label = (UILabel *)[cell viewWithTag:1];
    label.text = [NSString stringWithFormat:@"%@", myARObject.created_at];

    label = (UILabel *)[cell viewWithTag:2];
    label.text = [NSString stringWithFormat:@"%@", myARObject.articleTitle];

    label = (UILabel *)[cell viewWithTag:3];
    label.text = [NSString stringWithFormat:@"%@", myARObject.intro_text];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tblView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 105.0;
}