UITableViewCell проблема indexPath.row не отображается правильно - PullRequest
1 голос
/ 28 апреля 2011

Я настроил UITableView, который имеет 3 раздела, по 3 строки в каждом.Я использовал следующий код, чтобы указать, что я хочу, чтобы объекты из определенных массивов отображались как содержимое строки:

    recipeData = [[NSArray alloc] initWithObjects:@"Chicken & Veg Rissoto",@"Super Healthy Pizza",@"Salmon Burgers",nil];
    dessertsData = [[NSArray alloc] initWithObjects:@"Raspberry Parfaits",@"ChocNana YumYum",@"Grilled Choc Sandwich",nil];
    beveragesData = [[NSArray alloc] initWithObjects:@"Berry Smoothie",@"Banana Berry Smoothie",@"Cocoa Soy Smoothie",nil];
    [self setTitle:@"Recipe Table"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.recipeData count];
    return [self.dessertsData count];
    return [self.beveragesData count];

Это все работало нормально, до вечера, когда я добавил изображения слева оттекст в строке.Изображения отображаются идеально, но по какой-то причине все строки заполнены объектами из напитковData, и это полностью игнорирует два других набора объектов.Код ниже, который я использовал.Я надеюсь, что это так же просто, как просто написать оператор if неправильно.

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

    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];

    if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SimpleTableIdentifier] autorelease];
    }   
    if(indexPath.section == 0) 
        if(indexPath.row == 0)
            [cell.imageView setImage:[UIImage imageNamed:@"Main0.png"]];
            [cell.textLabel setText:[recipeData objectAtIndex:indexPath.row]];
    if(indexPath.section == 0) 
        if(indexPath.row == 1)
            [cell.imageView setImage:[UIImage imageNamed:@"Main1.png"]];
            [cell.textLabel setText:[recipeData objectAtIndex:indexPath.row]];
    if(indexPath.section == 0)
        if(indexPath.row == 2)
            [cell.imageView setImage:[UIImage imageNamed:@"Main2.png"]];
            [cell.textLabel setText:[recipeData objectAtIndex:indexPath.row]];

   if(indexPath.section == 1)
        if(indexPath.row == 0)
            [cell.imageView setImage:[UIImage imageNamed:@"Dessert0.png"]];
            [cell.textLabel setText:[dessertsData objectAtIndex:indexPath.row]];
    if(indexPath.section == 1)
        if(indexPath.row == 1)
            [cell.imageView setImage:[UIImage imageNamed:@"Dessert1.png"]];
            [cell.textLabel setText:[dessertsData objectAtIndex:indexPath.row]];
    if(indexPath.section == 1)
        if(indexPath.row == 2)
            [cell.imageView setImage:[UIImage imageNamed:@"Dessert2.png"]];
            [cell.textLabel setText:[dessertsData objectAtIndex:indexPath.row]];

   if (indexPath.section == 2)
        if(indexPath.row == 0)
            [cell.imageView setImage:[UIImage imageNamed:@"Drink0.png"]];
            [cell.textLabel setText:[beveragesData objectAtIndex:indexPath.row]];
    if(indexPath.section == 2)
        if(indexPath.row == 1)
            [cell.imageView setImage:[UIImage imageNamed:@"Drink1.png"]];
            [cell.textLabel setText:[beveragesData objectAtIndex:indexPath.row]];
    if(indexPath.section == 2)
        if(indexPath.row == 2)
            [cell.imageView setImage:[UIImage imageNamed:@"Drink2.png"]];
            [cell.textLabel setText:[beveragesData objectAtIndex:indexPath.row]];
    return cell;

Так что в настоящее время при запуске все 9 строк UITableView заполняются объектами из напитковData.Любая помощь будет принята с благодарностью.

Спасибо

Ответы [ 3 ]

1 голос
/ 28 апреля 2011

Ваш numberOfRowsInSection: раздел также неверен; должно быть:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ( section == 0 )        
        return [self.recipeData count];
    if ( section == 1 )
        return [self.dessertsData count];
    if ( section == 3 )
        return [self.beveragesData count];
}
1 голос
/ 28 апреля 2011

Структура Objective-c не основана на отступе

Это:

if(indexPath.section == 0) 
        if(indexPath.row == 0)
            [cell.imageView setImage:[UIImage imageNamed:@"Main0.png"]];
            [cell.textLabel setText:[recipeData objectAtIndex:indexPath.row]];

Должно быть:

if(indexPath.section == 0) 
        if(indexPath.row == 0) {
            [cell.imageView setImage:[UIImage imageNamed:@"Main0.png"]];
            [cell.textLabel setText:[recipeData objectAtIndex:indexPath.row]];
        }

Это похоже на C / C ++ / Java -- if относится к следующему утверждению.Если вам нужно больше, чем один, вы должны заключить выражения в фигурные скобки.Вы также можете постоянно вставлять в кудряшки, чтобы не волноваться об этом.

Кроме того, этот код

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.recipeData count];
    return [self.dessertsData count];
    return [self.beveragesData count];
}

не делает то, что вы думаете, что он делает.Первый возврат всегда выполняется, а вторые две строки игнорируются (должно быть получено предупреждение об этом).

0 голосов
/ 28 апреля 2011

Вы также должны использовать оператор switch:

switch ( indexPath.section ) 
{
    case 0:
    {
        if(indexPath.row == 0) {
            [cell.imageView setImage:[UIImage imageNamed:@"Main0.png"]];
            [cell.textLabel setText:[recipeData objectAtIndex:indexPath.row]];
        }
        if(indexPath.row == 1) {
            [cell.imageView setImage:[UIImage imageNamed:@"Main1.png"]];
            [cell.textLabel setText:[recipeData objectAtIndex:indexPath.row]];
        }
        if(indexPath.row == 2) {
            [cell.imageView setImage:[UIImage imageNamed:@"Main2.png"]];
            [cell.textLabel setText:[recipeData objectAtIndex:indexPath.row]];
        }
    }
}

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