简体   繁体   中英

How can I add/remove a cell from grouped section uitableview?

How can I programmatically add or remove a cell from a grouped section?

I created a grouped tableview using static cells in storyboard. Inside the storyboard I set the number of rows using the Attribute Inspector panel. For example, for section 1, I define 3 rows. Then using an NSMutableArray of 3 items, I can properly load values into each section correctly at startup.

I ultimately want the ability to add/remove a cell at runtime. That part hasn't been coded yet but to simulate adding a new cell scenario, I added a new item to the array in the code but did not increase the row count for the section in the Attribute Inspector panel. I had hoped that I would not need to make any other changes to accomodate the new item since inside the numberOfRowsInSection method, I'm returning the count of the array for the specific section.

This is the error message that I get when I re-ran the code:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 2]'

Apparently I need to somehow specify an additional row count. Can anyone shed some light on how I can do this at runtime? Thanks.

You should not do it through attribute inspector. it abstains you to do dynamic insertion and deletion of cells. try

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

else do this.

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
       return 3;
    }else if(section==1){
       return 4;
    }
 return 0;
}

and so on for different section if u have many section.. you can reload the whole table when you array from which data is read is updated..

[tableView reloadData];

but a better way to do it is to insert row or multiple rows like this in a block.

[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:yourIndexPath withRowAnimation:UITableViewRowAnimationRight];
[tableView endUpdates];

you can also add animation to add cell from right or lect or top or bottom.

I hope this helps you!! Cheers!!

I guess that you hardcoded the number of rows for your section. Because looking at the error it seems that your section is expecting 4 object but your data source contains only 3.

Inside your :

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

you should return something like [myArray count], so adding or delting rows shouldn't be a problem if you add or remove the object from your array.

UITableview中有用于插入和删除行的预定义方法,对于插入,我们可以使用insertRowAtIndexPath方法,对于删除,可以使用deleteRowAtIndexPath方法。

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