简体   繁体   中英

Add static cell in dynamic tableview

i am trying to add a static cell as the first cell in my dynamic tableview. I have seen other questions on here but they do not seem to work. Any help is greatly appreciated. I actually get my cell, but it is replacing my first dynamic cell and when i scroll in my table view, my app crashes.

Here is what i have arrived at so far:

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


static NSString *CellIdentifier = @"Cell"; 
 CustomSideBarCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (indexPath.row < NUMBER_OF_STATIC_CELLS) { 

cell.sidePic.image = _secondImage; 
cell.sideOption.text = @"Everything"; 

return cell; 

} 

else { 

cell.sidePic.image = _secondImage; 
_tempResults = [_tableData objectAtIndex:indexPath.row]; 
_optionCategory = [[_tempResults objectForKey:@"post"] objectForKey:@"category_name"]; 
cell.sideOption.text = _optionCategory; 

I think your problem is that you're accessing your _tableData with indexPath.row which starts at NUMBER_OF_STATIC_CELLS after you created all static cells.

Let's assume you have 4 static cells and 6 dynamic cells. That's a total of 10 cells. So after creating all static cells ( indexPath.row = 0 - 3 ) it will create the dynamic cells with indexPath.row = 4 - 9 even though your dataSource ( _tableData ) only has 6 elements. That's why you have to subtract the number of static cells when accessing _tableData .

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  { 
    static NSString *CellIdentifier = @"Cell"; 
    CustomSideBarCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    //static cell
    if (indexPath.row < NUMBER_OF_STATIC_CELLS) { 
        cell.sidePic.image = _secondImage; 
        cell.sideOption.text = @"Everything"; 
        return cell; 
    }

    //dynamic cell
    cell.sidePic.image = _secondImage;
    //subtract the number of static rows to start at 0 for your dataSource
    _tempResults = [_tableData objectAtIndex:indexPath.row - NUMBER_OF_STATIC_CELLS]; 
    _optionCategory = [[_tempResults objectForKey:@"post"] objectForKey:@"category_name"]; 
    cell.sideOption.text = _optionCategory; 
    return cell;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM