Обновление TableView клетки
-
14-11-2019 - |
Вопрос
Я все еще очень зеленый, как объект-C, так что, надеюсь, я могу общаться с этим хорошо, поэтому, надеюсь, с моими примерами кода я могу это объяснить.
Что у меня есть, это стол с четырьмя рядами. Каждая строка имеет метку (часы вовремя, выход на обед, и т. Д.) И временем (подробноеeextLabel). Этикетки хранятся в массиве, а детали генерируются из семейства функций NSDate (пожалуйста, прости мою терминологию). Чтобы изменить значения времени, я использую сборник данных, отрегулируемый для выбора времени. Действие используется для обновления детализации строки, когда время изменяется с помощью сборщика.
Последующие фрагменты кода находятся в том же * .m Класс.
Вот повернутая версия этого -
// textLabel goes on the left, detailTextLabel goes on the right
// This puts the labelArray on the left and times on the right
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCustomCellID = @"CustomCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCustomCellID] autorelease];
// This disable the hightlighter effect when we select a row.
// We need the highlighter, but we'll leave the code here.
// cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [self.labelArray objectAtIndex:indexPath.row];
// --- Start of routine to work with adding hours and minutes to stuff
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
// --- Set Clock In time (initially time 'now').
if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Clock In"])
{
self.clockIn = [NSDate date];
cell.detailTextLabel.text = [self.dateFormatter stringFromDate:clockIn];
NSLog(@"Clock In - %@", clockIn);
//NSLog(@"Clock In (cell*) - %@", cell.detailTextLabel.text);
return cell;
}
// --- Set Out to Lunch time (initially clockIn + 5 hours)
if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Out to Lunch"])
{
[offsetComponents setHour:5];
self.outToLunch = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
cell.detailTextLabel.text = [self.dateFormatter stringFromDate:outToLunch];
NSLog(@"indexPath.row (Out to Lunch): %i", indexPath.row);
NSLog(@"Out to Lunch - %@", outToLunch);
//NSLog(@"Out to Lunch (cell*) - %@", cell.detailTextLabel.text);
return cell;
}
// Leaving out two other if clauses as they duplicate the Out to Lunch clause.
//cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[NSDate date]];
//return cell;
return nil;
.
Этот кусок кода хорошо работает и не дает мне никаких проблем.
Когда ряд, такой как «часы в», выбран анимация, называется, что прокрутка вверх по времени сбора времени. Как время прокручиваются «часами в» обновлениях времени.
Вот где у меня проблема. Я не могу выяснить, как обновить ряд «на обед», как обновляется время «Часы в».
Вот код, который у меня есть для моего выбора действия -
- (IBAction)dateAction:(id)sender
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.detailTextLabel.text = [self.dateFormatter stringFromDate:self.pickerView.date];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
if (indexPath.row == [labelArray indexOfObjectIdenticalTo:@"Clock In"])
{
if (cell.detailTextLabel.text != [self.dateFormatter stringFromDate:clockIn])
{
NSLog(@"clockIn time changed...");
// Since clockIn time changed, we need to change outToLunch, inFromLunch, and clockOut
// Change the outToLunch time
[offsetComponents setHour:5];
self.outToLunch = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
dateByAddingComponents:offsetComponents toDate:self.pickerView.date options:0];
NSLog(@"New Out to Lunch time: %@", [self.dateFormatter stringFromDate:outToLunch]);
// Here is where I get stuck
}
//return nil;
}
}
.
Что я предполагаю, что «изменить время Outtolunch Time» - это что-то подобное ...
- Возьмите новое время Clockin и добавьте 5 часов к нему и сделайте это новое время Outtolunch. а. NSLog просто чтобы увидеть, что эта математическая функция работала.
- Использование индекса детализации TextLabel для ottolunch Time Cell, поместите это новое время там.
Там будет еще два ряда строк вместе с ottolunch Row, которая будет обновляться одновременно.
Как я могу сделать это?
Спасибо за вашу помощь.
Решение 2
После работы над этим с Timthetoolmanmanman Motelmanmanmanmanmanmanmanmanmanman Я нашел эту статью Stackoverflow: « Как выбрать Indexpath of UiableView после POP? ", который Томас ответил, что я использовал Следующие кусочки кода:
Добавлено в файл .h файл
NSIndexPath* outToLunchIndexPath;
//...
}
//...
@property (nonatomic, retain) NSIndexPath* outToLunchIndexPath;
//...
@end
.
Добавлено в файл .m
@synthesize outToLunchIndexPath;
.
Тогда в моем коде я добавил эти строки
self.outToLunch = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
dateByAddingComponents:offsetComponents toDate:self.pickerView.date options:0];
// New code...
UITableViewCell *outToLunchCell = [self.tableView cellForRowAtIndexPath:outToLunchIndex];
outToLunchCell.detailTextLabel.text = [self.dateFormatter stringFromDate:outToLunch];
NSLog(@"New Out to Lunch time: %@", [self.dateFormatter stringFromDate:outToLunch]);
.
Это имело влияние обновления содержимого Cell.detaillabel.Text исходного пространства, поскольку время Clockin изменилось с DatePicker.
Большое спасибо timthetoolman и Томас для их помощи.
Другие советы
В конце вашего - (Ibaction) Dataeaicate: (ID) Отправитель Используйте следующее:
// Here is where I get stuck
}
//return nil;
}
NSArray *indexPathArray=[NSArray arrayWithObject:indexPath];
[self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
}
.
В качестве альтернативы, вы можете использовать [Self.tableview ReloadData], но это перезарядки для простого перезагрузки одной строки, особенно если количество строк, которые у вас есть, большой.