UILabel在cellForRowAtIndexPath中为零

时间:2014-08-25 01:15:37

标签: ios objective-c iphone uitableview

我正在使用Storyboard的原型单元格和自定义表格单元格类,而且UILabel在cellForRowAtIndexPath中为零。 Xcode的标识符是正确的,单元格被初始化,默认的UILabel(即textLabel和detailTextLabel)被初始化,但不是我添加的自定义UILabels并设置了IBOutlets。我尝试了几件事:

  • 我尝试删除ViewDidLoad中的registerClass调用但由于单元格需要将其初始化为自定义类GenericDetailCell而崩溃。

  • viewWithTag返回nil

  • 我尝试遍历UITableView的所有子视图,看看我是否得到了错误的单元格。 dequeueReusableCellWithIdentifier

  • 返回正确的单元格

有没有人碰到这个?

@implementation PeopleGroupPickerViewController
{
    NSArray *people;
    NSArray *searchResults;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    people = [[DAL sharedInstance] getPeople:false];
    [self.tableView registerClass:[GenericDetailCell class] forCellReuseIdentifier:@"PersonCell"];
    [self.searchDisplayController.searchResultsTableView registerClass:[GenericDetailCell class] forCellReuseIdentifier:@"PersonCell"];

    // stackoverflow.com/questions/5474529
    [self.searchDisplayController setActive:YES];
    [self.searchDisplayController.searchBar becomeFirstResponder];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView == self.searchDisplayController.searchResultsTableView)
    {
        return 1;
    }
    else
    {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == self.searchDisplayController.searchResultsTableView)
    {
        return searchResults.count;
    }
    else
    {
        return people.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GenericDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonCell" forIndexPath:indexPath];

    Person_ *thisPerson;
    if(tableView == self.searchDisplayController.searchResultsTableView)
    {
        thisPerson = (Person_ *) searchResults[indexPath.row];
        NSLog(@"searchResultsTableView, %@",thisPerson.sName);
    }
    else
    {
        thisPerson = (Person_ *) people[indexPath.row];
        NSLog(@"UITableView, %@",thisPerson.sName);
    }
    Person_ *thisSpouse = [[DAL sharedInstance] getSpouse:thisPerson People:people];

    // cell.fieldName and cell.fieldValue are nil, cell is not nil
    cell.fieldName.text = thisPerson.sName;
    cell.fieldValue.text = thisSpouse.sName;

    return cell;
}

GenericDetailCell.h:

@interface GenericDetailCell : UITableViewCell

@property (nonatomic,weak) IBOutlet UILabel *fieldName;
@property (nonatomic,weak) IBOutlet UILabel *fieldValue;

@end

1 个答案:

答案 0 :(得分:2)

在我看来,您可能正在尝试将UITableViewCell预定义样式(例如UITableViewCellStyleSubtitle)与自定义单元格结合使用。

在故事板中,如果您为Prototype单元格选择了预定义样式,则无法识别其他控件。

要解决此问题,请在原型UITableViewCell的属性检查器中,选择"自定义"类型。然后将所需的所有控件添加到Prototype单元格中,包括将先前自动添加到预定义单元格类型中的默认控件替换所需的控件。

相关问题