Два разных UITableViewCell в UITableView

Я хочу создать один TableView с двумя строками раздела. эта таблица имеет 2 раздела (первый раздел имеет 1 ячейку, а второй раздел имеет 3 ячейки)

обратите внимание: ячейка первого раздела отличается от ячеек второго раздела.

это мой код, но он не работает!!!

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

    NSArray *name = [_names objectForKey:key];
    static NSString *CellIdentifier2 = @"CustomerCell";

    if (indexPath.section == 0) {

        static NSString *CellIdentifier = @"myCell";
        FirstCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[FirstCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        // Configure the cell...
        cell.nameLable.text = [NSString stringWithFormat:@"blue"];
        cell.numberLable.text = [NSString stringWithFormat:@"1212432543"];
        cell.profileImage.image = [UIImage imageNamed: @"profile.png"];

        return cell;
//this part not working !!! XD

    }
    else if (indexPath.section >= 1) {

        CustomerCell *cell = (CustomerCell *)[self.table dequeueReusableCellWithIdentifier:CellIdentifier2];
        if (cell == nil)
        {
            NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:@"CustomerCell" owner:nil options:nil];

            for (id currentObject in topLevelObject) {
                if ([currentObject isKindOfClass:[CustomerCell class]]) {
                    cell = (CustomerCell *)currentObject;
                    break;
                }
            }
        }
        // Configure the cell...
        cell.titleLable.text = [name objectAtIndex:indexPath.row];
        return cell;
    }
    return nil;
}

customerCell и FirstCell — два UITableViewCell для пользовательских ячеек. когда я запускаю этот код, только один раздел не работает и не показывает ячейку, но другой раздел работает, пожалуйста, направьте меня и скажите, в чем моя ошибка.


person Mohammad Kasiri    schedule 07.04.2014    source источник
comment
Я думаю, проблема здесь: cell = [[FirstCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; вы должны загрузить перо, как вы сделали для второго раздела.   -  person Pooja M. Bohora    schedule 07.04.2014
comment
@PoojaM.Bohora Не нужно загружать перо, это может быть собственный класс для UITableViewCell.   -  person iphonic    schedule 07.04.2014
comment
@iphonic: он не использует свой xib при создании firstcell. Аспер его реализация была просто догадкой. Так как я не видел полного кода.   -  person Pooja M. Bohora    schedule 07.04.2014
comment
@PoojaM.Bohora Разве это не то же самое, что [[UITableViewCell alloc] init], где UITableViewCell == FirstCell?   -  person iphonic    schedule 07.04.2014
comment
@iphonic: зависит от его подхода, поскольку он создал ячейку по-разному для второго раздела. Пусть один раз проверит.   -  person Pooja M. Bohora    schedule 07.04.2014
comment
NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:@"CustomerCell" owner:nil options:nil]; разве это не должно быть owner:self вместо nil ?   -  person TheTiger    schedule 07.04.2014
comment
ребята я так запутался!!! У FirstCell и customerCell есть файл xib, и я загружаю ячейку оттуда!!!   -  person Mohammad Kasiri    schedule 07.04.2014
comment
@mamal10: Ты решил свою проблему или нет?   -  person Pooja M. Bohora    schedule 07.04.2014
comment
Я не могу решить свою проблему.   -  person Mohammad Kasiri    schedule 07.04.2014
comment
@mamal10: попробуйте это FirstCell *cell = (FirstCell *)[tableView dequeueReusableCellWithIdentifier:strEvalIdentifier]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@FirstCell owner:self options:nil]; ячейка = [перо objectAtIndex:0]; }   -  person Pooja M. Bohora    schedule 07.04.2014
comment
подскажите, пожалуйста, как использовать 2 TableViewCell в одном табличном представлении   -  person Mohammad Kasiri    schedule 07.04.2014


Ответы (2)


Попробуй это:

FirstCell *cell = (FirstCell *)[tableView dequeueReusableCellWithIdentifier:strEvalIdentifier]; 
if (cell == nil)
{
   NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FirstCell" owner:self options:nil];
   cell = [nib objectAtIndex:0];
} 
person Pooja M. Bohora    schedule 07.04.2014
comment
снова мое приложение разбилось на этой строке: NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@FirstCell owner:self options:nil]; - person Mohammad Kasiri; 07.04.2014
comment
@ mamal10 Пожалуйста, причину сбоя? - person Pooja M. Bohora; 07.04.2014
comment
Я не знаю причину сбоя, но выведите эту ошибку в консоль: libc++abi.dylib: завершение с необработанным исключением типа NSException (lldb) - person Mohammad Kasiri; 07.04.2014
comment
Не могли бы вы отредактировать свой пост и вставить необходимый код? - person Pooja M. Bohora; 07.04.2014
comment
подождите несколько минут, теперь поместите весь проект - person Mohammad Kasiri; 07.04.2014
comment
@mamal10: В чем была проблема? - person Pooja M. Bohora; 07.04.2014
comment
ваш код правильный, но мой xcode завис, когда я удаляю класс FirstCell и создаю его снова, этот код работает!!! :D - person Mohammad Kasiri; 07.04.2014
comment
@mamal10: Бывает без проблем. - person Pooja M. Bohora; 07.04.2014

Попробуйте использовать тот же код, что и во второй ячейке.

if (indexPath.section == 0) {
FirstCell *cell = (FirstCell *)[self.table dequeueReusableCellWithIdentifier:CellIdentifier2];
    if (cell == nil)
    {
        NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:@"FirstCell" owner:nil options:nil];

        for (id currentObject in topLevelObject) {
            if ([currentObject isKindOfClass:[FirstCell class]]) {
                cell = (FirstCell *)currentObject;
                break;
            }
        }
// Configure the cell...
    cell.nameLable.text = [NSString stringWithFormat:@"blue"];
    cell.numberLable.text = [NSString stringWithFormat:@"1212432543"];
    cell.profileImage.image = [UIImage imageNamed: @"profile.png"];

    return cell;
    }
person borncrazy    schedule 07.04.2014
comment
Не отвечайте в спешке. if ([currentObject isKindOfClass:[класс CustomerCell]] должен быть if ([currentObject isKindOfClass:[класс FirstCell]] - person Pooja M. Bohora; 07.04.2014
comment
Сделал подмену. Спасибо. - person borncrazy; 07.04.2014
comment
мое приложение разбилось в этой строке: NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:@FirstCell owner:nil options:nil]; - person Mohammad Kasiri; 07.04.2014
comment
да, мой чувак и мое приложение разбились на этой строке: NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:@FirstCell owner:nil options:nil]; - person Mohammad Kasiri; 07.04.2014
comment
@mamal10: Вы игнорируете мое заявление, его владелец? и не ноль. - person Pooja M. Bohora; 07.04.2014
comment
Когда вы говорите крушение. Упомяните также журнал сбоев. Так что мы можем помочь вам в этом. - person Pooja M. Bohora; 07.04.2014
comment
@mamal вы уверены, что ваше имя файла пера — FirstCell, а также попробуйте изменить параметр владельца на self. - person borncrazy; 07.04.2014