Когда приходит пустое поле, удалили строку в сгруппированной таблице в iPhone?
-
24-10-2019 - |
Вопрос
Я отобразил данные в сгруппированном представлении таблицы. Данные отображаются в представлении таблицы из XML -анализа. У меня есть 2 секции представления о таблице, в разделе One есть три ряда, а в втором разделе есть два ряда.
section 1 -> 3 Rows
section 2 - > 2 Rows.
Теперь я хочу проверить, если кто -то из строки пуст, я должен удалить пустые ячейки, поэтому я столкнулся с некоторыми проблемами, если я удалил какую -либо пустую ячейку, то это изменит номер индекса. Итак, как я могу проверить, кто -нибудь из поля пусто? Итак, пожалуйста, пришлите мне пример кода или ссылки для этого? Как я могу этого добиться?
Образец кода,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0) {
if([userEmail isEqualToString:@" "] || [phoneNumber isEqualToString:@" "] || [firstName isEqualToString:@" "])
{
return 2;
}
else {
return 3;
}
}
if (section == 1) {
if(![gradYear isEqualToString:@" "] || ![graduate isEqualToString:@" "]) {
return 1;
}
else
{
return 2;
}
return 0;
}
Пожалуйста, помогите мне !!!
Спасибо.
Решение
Насколько я понимаю, вы не хотите добавлять строку, в которой данные пусты, поэтому я предполагаю, что вы должны лишить данные разделов, прежде чем сообщать о том, что в разделах и строки.
Таким образом, может быть следующим кодом, может помочь вам ..., я протестировал его, вам просто нужно вызвать метод «PrepareSectionData» из метода «ViewDidload» и определить массивы разделов в .h -файл.
- (void) prepareSectionData {
NSString *userEmail = @"";
NSString *phoneNumber = @"";
NSString *firstName = @"";
NSString *gradYear = @"";
NSString *graduate = @"";
sectionOneArray = [[NSMutableArray alloc] init];
[self isEmpty:userEmail]?:[sectionOneArray addObject:userEmail];
[self isEmpty:phoneNumber]?:[sectionOneArray addObject:phoneNumber];
[self isEmpty:firstName]?:[sectionOneArray addObject:firstName];
sectionTwoArray = [[NSMutableArray alloc] init];
[self isEmpty:gradYear]?:[sectionTwoArray addObject:gradYear];
[self isEmpty:graduate]?:[sectionTwoArray addObject:graduate];
}
-(BOOL) isEmpty :(NSString*)str{
if(str == nil || [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)
return YES;
return NO;
}
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0){
return [sectionOneArray count];
} else if (section == 1) {
return [sectionTwoArray count];
}
return 0;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
if(indexPath.section == 0){
cell.textLabel.text = [sectionOneArray objectAtIndex:indexPath.row];
} else if (indexPath.section == 1) {
cell.textLabel.text = [sectionTwoArray objectAtIndex:indexPath.row];
}
return cell;
}
Другие советы
@Pugal Devan, ну, вы можете сохранить данные в одном массиве, но проблема в этом случае в том, что вы должны позаботиться о границах массива и правильных индексах для различных разделах. Для каждого раздела IndexPath.Row будет начинаться с индекса 0, и если ваши данные находятся в одном массиве, вы должны управлять индексом строки сами. Но все же, если вы хотите сохранить это, вы можете сделать:
int sectionOneIndex = 0;
int sectionTwoIndex = 3;
NSMutableArray *sectionArray = [[NSMutableArray alloc] initWithObjects:@"email", @"Name", @"address", @"zipCode", @"country", nil];
Выше двух целых чисел представляют собой начальную позицию элементов ваших различных разделов. Первые 3 объекта из массива разделов являются частью первого раздела, а последние два объекта являются частью второго раздела. Теперь вам нужно вернуть правильное количество строк. Для этого вы можете написать:
if(section == 0) return [sectionArray count] - (sectionTwoIndex-1); //returns 3
else if(section == 1) return [sectionArray count] - sectionTwoIndex; //returns 2
Или, если ваш счет статичен, вы можете поставить постоянные значения взамен.
И в то время, когда вы читаете из массива, вы просто добавите этот индекс в значении строки, что вернет правильное положение вашего элемента для текущей ячейки.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
if(indexPath.section == 0){
cell.textLabel.text = [sectionArray objectAtIndex:indexPath.row + sectionOneIndex];
} else if (indexPath.section == 1) {
cell.textLabel.text = [sectionArray objectAtIndex:indexPath.row + sectionTwoIndex];
}
return cell;
}