How to insert a cell in a TableView

Discussion in 'iOS Programming' started by sergio27, Nov 2, 2008.

  1. sergio27 macrumors member

    Nov 2, 2008
    Hello. I suppose this should be very easy, but I'm stuck and I need your help.

    I'm working in a "Utility Application". In the main view I have a TextField, a Button and a TableView. This TableView is filled with items on an array. All I want is to write something in the text field, and add that text as a new cell in the TableView.

    The "cellForRowAtIndexPath" loads correctly the table with the values in the array at the begining, but it is not called when I add more items to the array. I have tried the following:

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.array addObject:textInput.text];

    NSIndexPath *ip = [NSIndexPath indexPathForRow:num inSection:0];
    NSArray *arr = [NSArray arrayWithObject:(NSIndexPath *)ip];
    [tableView insertRowsAtIndexPaths:arr withRowAnimation:YES];

    Also, I tried calling [tableView reload]. In both cases, the array adds the item correctly, but the TableView doesn't show the changes.

    I have read the documentation and checked the samples, but I haven't found one where the items are inserted entirely with code. I would appreciate your help. Thank you.
  2. laprej macrumors regular

    Oct 14, 2005
    Troy, NY
    You need to use an NSMutableArray, not an NSArray, which cannot be changed after creation. Then you simply add another piece of data to your NSMutableArray and then call reloadData.
  3. beachdog macrumors member

    Aug 10, 2008
    I think you've got it backwards. You don't explicitly insert cells into a Tableview. Instead, you write a class which is the datasource of the TableView (delegate as well, usually) and then you simply respond to the method calls wherein the TableView asks you how many rows should be displayed, and what should be the content of each row. See the docs on UITableView with attention to the UITableViewDelegate protocol

Share This Page