Adding cells programmatically to UITableView

前端 未结 4 1996
难免孤独
难免孤独 2020-12-13 22:09

I\'ve just recently started programming for the iPhone and I\'m making an application that connects to a database and gets a set of row names and displays them. When selecte

4条回答
  •  庸人自扰
    2020-12-13 22:24

    Don't need to use insertRowsAtIndexPaths.

    Check: UITableViewDataSource Protocol Reference and UITableView Class Reference

    The magic happens between this three methods (UITableViewDataSource protocol methods):

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
    

    You just need to fill an array. Yes it can be a NSMutableArray.

    You can fill the array in - (void)viewDidLoad, for example:

    yourItemsArray = [[NSMutableArray alloc] initWithObjects:@"item 01", @"item 02", @"item 03", nil];
    

    And them use the data source methods like this:

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        // Return the number of sections.
        // If You have only one(1) section, return 1, otherwise you must handle sections
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        // Return the number of rows in the section.
        return [yourItemsArray count];
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
    
        // Configure the cell...
        cell.textLabel.text = [yourItemsArray objectAtIndex:indexPath.row];
    
        return cell;
    }
    

    Like this cells will be created automatically.

    If You chage the Array, just need to call:

    [self.tableView reloadData];
    

提交回复
热议问题