iOS - UIDatePicker изменяет отображаемую дату динамически
Я использую код из примера DateCell, и я хочу изменить дату в начале на дату, которую я выбираю (я загружаю откуда-то). Поэтому я меняю значение даты в dataArray
(словарь с kTitleKey
а также kDateKey
) И в dateCell
это нормально. Там показана моя дата, но когда я нажал на эту ячейку DatePicker
и отображается дата по умолчанию от StoryBoard. Я предполагаю, что проблема в методе updateDatePicker:
- (void)updateDatePicker
{
if (self.datePickerIndexPath != nil)
{
UITableViewCell *associatedDatePickerCell = [datePickersTableView cellForRowAtIndexPath:self.datePickerIndexPath];
/*
if (associatedDatePickerCell == nil) {
associatedDatePickerCell = [datePickersTableView dequeueReusableCellWithIdentifier:kDatePickerID];
}*/
UIDatePicker *targetedDatePicker = (UIDatePicker *)[associatedDatePickerCell viewWithTag:kDatePickerTag];
if (targetedDatePicker != nil)
{
// we found a UIDatePicker in this cell, so update it's date value
//
NSDictionary *itemData = self.dataArray[self.datePickerIndexPath.row - 1];
[targetedDatePicker setDate:[itemData valueForKey:kDateKey] animated:NO];
}
}
}
По какой-то причине relatedDatePickerCell всегда равен нулю. Я пытался изменить его (с кодом в комментариях), но это не помогло (relatedDatepickerCell тогда не было нулем, но дата все еще не менялась). У меня есть правильная дата в itemData
,
Изменить: добавлен код для cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
NSString *cellID;
if ([self indexPathHasPicker:indexPath])
{
// the indexPath is the one containing the inline date picker
cellID = kDatePickerID; // the current/opened date picker cell
}
else
{
// the indexPath is one that contains the date information
cellID = kDateCellID; // the start/end date cells
}
//if ([self indexPathHasDate:indexPath])
cell = [tableView dequeueReusableCellWithIdentifier:cellID];
// if we have a date picker open whose cell is above the cell we want to update,
// then we have one more cell than the model allows
//
NSInteger modelRow = indexPath.row;
if (self.datePickerIndexPath != nil && self.datePickerIndexPath.row < indexPath.row)
{
modelRow--;
}
// proceed to configure our cell
if ([cellID isEqualToString:kDateCellID])
{
NSDictionary *itemData = self.dataArray[modelRow];
// we have either start or end date cells, populate their date field
//
cell.textLabel.text = [itemData valueForKey:kTitleKey];
UILabel *custLabel = (UILabel*)[cell viewWithTag:2];
custLabel.text = [self.dateFormatter stringFromDate:[itemData valueForKey:kDateKey]];
UIView *dateView = (UIView*)[cell viewWithTag:3];
[dateView.layer setBorderWidth:1];
[dateView.layer setBorderColor:[[UIColor whiteColor] CGColor]];
cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[itemData valueForKey:kDateKey]];
}
[cell setBackgroundColor:[UIColor clearColor]];
return cell;
}
2 ответа
Кто зовет тебя updateDatePicker
метод?
Проблема в том, что при его реализации вы пытаетесь получить ячейку с cellForRowAtIndexPath:
который может или не может вернуть ячейку в зависимости от времени, положения прокрутки и т. д.:
Возвращаемое значение
Объект, представляющий ячейку таблицы или nil, если ячейка не видна или indexPath находится вне диапазона.
Вы должны обновить сборщик при возврате соответствующей ячейки в tableViewDataSource
внутри вашего tableView:cellForRowAtIndexPath:
, который будет вызываться лениво представлением таблицы только при необходимости.
Убедитесь, что ваш cellForRowAtIndexPath
имеет код, который выглядит так:
[tableView dequeueReusableCellWithIdentifier:@"Cell"];
И вы зарегистрировали класс или перо, вызывающее методы tableViews (например, в viewDidLoad):
– registerNib:forCellReuseIdentifier:
– registerClass:forCellReuseIdentifier:
Так что актуальная проблема у вас cellForRowForIndexPath:
,