iOS: uitableview с несколькими динамическими секциями - PullRequest
0 голосов
/ 04 января 2019

Я получаю ответ API. Я хочу поместить все эти данные в UITableView с разделом. Я создаю Массив для заголовка заголовка, но сейчас я пытаюсь, но не могу создать Массив для внутренних данных, которые я должен показать в ячейках.,Пожалуйста, помогите мне заполнить эти данные в виде таблицы разделами.

   {
        "sponsers": {
            "ORGANISED BY": [
                {
                    "id": "27",
                    "sp_name": "www.****.my",
                    "sp_logo": "499270053_logo2.png",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "1"
                },
                {
                    "id": "29",
                    "sp_name": "www.anderesfourdy.com",
                    "sp_logo": "157207241_my-partner.png",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "1"
                },
                {
                    "id": "30",
                    "sp_name": "visitpenang.com.my",
                    "sp_logo": "730893130_logo1.png",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "1"
                }
            ],
            "OFFICIAL VENUE PARTNER": [
                {
                    "id": "32",
                    "sp_name": "www.setiaspice.com",
                    "sp_logo": "2116042847_eda576900989f3222d77c7d511c77dcc.jpg",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "2"
                }
            ],
            "OFFICIAL AIRLINE PARTNER": [
                {
                    "id": "33",
                    "sp_name": "www.malaysiaairlines.com/in/en.html",
                    "sp_logo": "475052144_276e3235a63924f1922e703d4a8b31a6.png",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "3"
                }
            ],
            "HOTEL PARTNERS": [
                {
                    "id": "34",
                    "sp_name": "olivetreehotel.com.my",
                    "sp_logo": "97088892_3cdc275c1942eeb186d6920abd300611.jpg",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "4"
                },
                {
                    "id": "35",
                    "sp_name": "penang.equatorial.com",
                    "sp_logo": "622248930_5deb8b605822d4b5cea4e122b55dcbdd.jpg",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "4"
                },
                {
                    "id": "36",
                    "sp_name": "www.beatpenang.com/www.shangri-la.com/penang/rasasayangresort",
                    "sp_logo": "918729310_38d4aca7a13e8e65885aa690835219f5.png",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "4"
                },
                {
                    "id": "37",
                    "sp_name": "www.beatpenang.com/www.vistanahotels.com/penang",
                    "sp_logo": "1497393994_66eb81f97563446cb2b1c743e5d69b99.jpg",
                    "events": "24",
                    "priority": "0",
                    "status": "1",
                    "s_type": "4"
                }
            ],..........

Я использую следующий код для отображения данных в виде таблицы: DataArray содержит значения внутри ключа «спонсоры»

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [DataArray count];
}


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [DataArray objectAtIndex:section];
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[DataArray objectAtIndex:section] count];
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    cell.textLabel.font=[UIFont fontWithName: @"Arial" size: 14.0 ];

    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;

    //to hide extra cell from table
    sponsorTable.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    /*UIView * bkView = (UIView*)[cell viewWithTag:150];
    if(indexPath.row % 2 == 0)
    {
        bkView.backgroundColor = [UIColor whiteColor];
        //cell.backgroundColor = [UIColor whiteColor];
    }
    else
    {
        bkView.backgroundColor = [UIColor colorWithRed:234/255.0 green:236/255.0 blue:235/255.0 alpha:1];
    }*/



    NSString* name = [[DataArray objectAtIndex:indexPath.row]valueForKey:@"sp_name"];
    NSLog(@"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=%@",name);
    UILabel * nameLbl = (UILabel *)[cell viewWithTag:102];
    nameLbl.text = name;



    NSString * urlstring = [[DataArray objectAtIndex:indexPath.row]valueForKey:@"sp_logo"];
    NSLog(@"urlStr is %@",urlstring);
    NSString * completeString = [NSString stringWithFormat:@"http:****************",urlstring];
    NSLog(@"Complete Url string is %@",completeString);
    UIImageView * imgVw = (UIImageView *)[cell viewWithTag:101];

    cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2;
    cell.imageView.clipsToBounds = YES;

    NSString *imageUrl = [NSString stringWithFormat:@"%@",completeString];
    dispatch_queue_t imageDownloadQueue = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, nil);

    dispatch_async(imageDownloadQueue, ^{
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];

        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage * image1 = [UIImage imageWithData:imageData];
            imgVw.image = image1;
        });
    });


    return cell;
}

Ответы [ 2 ]

0 голосов
/ 04 января 2019

Вы должны установить конкретный ключ, и этот ключ вы должны сохранить «значение раздела». Таким образом, вы можете легко получить значение раздела. ваш словарь установлен, как показано ниже.

"data" : [
    {
      “Section Title“ : “Section1”,
      “InnerCellData” : [
        {
        //record 1
        }
       {
        //record 2
        }
      ]
    }
    {
      “Section Title“ : “Section2”,
      “InnerCellData” : [
        {
        //record 1
        }
       {
        //record 2
        }
      ]
    }

  ]

Это работает для вас.

0 голосов
/ 04 января 2019

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSDictionary *sponsers = parsedResponse[@"sponsers"];
    return sponsers.allKeys.count; // For every key we need a section
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary *sponsers = parsedResponse[@"sponsers"];
    NSString *key = sponsers.allKeys[section];
    return key; // The key is the section name

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *sponsers = parsedResponse[@"sponsers"];
    NSString *key = sponsers.allKeys[section];
    NSArray *content = sponsers[key]; // Each item should be an array
    return content.count; // Return number of items in embedded array
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *sponsers = parsedResponse[@"sponsers"];
    NSString *key = sponsers.allKeys[indexPath.section];
    NSArray *content = sponsers[key];
    NSDictionary *item = content[indexPath.row];
    // We have the item. Populate the cell
    ... generate cell ...
    cell.textLabel.text = item[@"sp_name"];
    ...
}

Это должна быть вся информация, необходимая для построения представления таблицы.Если у вас есть проблемы с заполнением данных ячейки, я предлагаю вам задать еще один конкретный вопрос по этому поводу.

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