Ячейка UITableView, возвращающая ноль значений свойств - PullRequest
2 голосов
/ 26 марта 2012

У меня есть следующее:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if(indexPath.row==0)
    {
        static NSString *CellID = @"FlourishCustomCell";
        FlourishCustomCell *cell = (FlourishCustomCell *) [tableView dequeueReusableCellWithIdentifier:CellID];
        if (cell == nil) {
            cell = [[[FlourishCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID] autorelease];
            cell.frame = CGRectMake(0, 0.0, 292.0, 30);
        }

        id <NSFetchedResultsSectionInfo> sectionInfo = 
        [[appDelegate.fetchedResultsController sections] objectAtIndex:indexPath.section];
        NSLog(@"DATE:%@", [sectionInfo name]); //Output: March 25

        cell.dateLabel.text=[sectionInfo name];
        NSLog(@"header cell:%@", cell.dateLabel.text); //Output:header cell:(null)

        return cell;
    }
    else {
        static NSString *CellIdentifier = @"IdeaCustomCell";
        IdeaCustomCell *cell = (IdeaCustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[IdeaCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell.frame = CGRectMake(0, 0.0, 292.0, 70);
        }

        [self configureCell:cell atIndexPath:[self newIndexPathForIndexPath:indexPath]];
        return cell;
    }
}

Ячейки отображаются и работают нормально для части else (IdeaCustomCell), но по какой-то крайне неприятной причине, когда я установил dateLabelиз FlourishCell, а затем сразу же попытаться получить доступ к этому значению, я получаю значение null, хотя я просто установил его!И ячейка не отображается на экране.

Я попытался переопределить метод установки для dateLabel в классе FlourishCustomCell, и я поместил туда выражение NSLog, но по какой-то причине его никогда не вызывали.

Я понятия не имею, чтоможет быть причиной этого.Я имею в виду, я распределяю прямо там и тогда, но это все еще дает мне ноль.Есть идеи?

Ответы [ 2 ]

4 голосов
/ 26 марта 2012

Вам нужно инициализировать метку

Решение 1: Инициализация ячейки в коде

@interface FlourishCustomCell : UITableViewCell

@property (nonatomic, retain) UILable * dateLabel;

@end

@implementation FlourishCustomCell
@synthesize dateLabel = _dateLabel;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
   if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
   {
      _dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,300,50)];
      [self.contentView addSubview:_dateLabel]
   }

   return self; 
}

@end

Решение 2: Инициализация ячейки из nib

@interface FlourishCustomCell : UITableViewCell

@property (nonatomic, retain) UILable * dateLabel;

@end

@implementation FlourishCustomCell
@synthesize dateLabel = _dateLabel;

- (id)init
{
self = [[[[NSBundle mainBundle] loadNibNamed:@"YOUR_NIB_NAME" owner:nil options:nil] 
         lastObject] 
        retain];

   return self;
}

@end

РЕДАКТИРОВАТЬ : упс, забыл вернуть self при методе init, обновил ответ

0 голосов
/ 16 января 2014

У меня была такая же проблема при использовании перьев, у меня это работало

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *identifier = @"Cell";

CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
    NSString* nibFile = @"NibForCell";

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed: nibFile owner:nil options: nil];
    cell  = [topLevelObjects objectAtIndex: 0];
}

cell.cellText.text = @"test";

return cell;
}

просто убедитесь, что вы установили идентификатор повторного использования в свойствах пера

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...