Hilaj S L
Hilaj S L

Reputation: 2046

Add a new custom cell to the top of UITabelView

I tried more time to search but the result is not my wish. I have a UITableView with custom cells. And there is a button to add new cell to that UITableView. I can add new cell, but it will be added at bottom of the tableview.Thats why, I could not feel whether the cell is added or not. So I need to add the cell at the top the tableview.Please help me.enter image description here

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.firstArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    documentsRemarksTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        NSArray *nib=[[NSBundle mainBundle]loadNibNamed:@"documentsRemarksTableCell" owner:self options:nil];
        cell=[nib objectAtIndex:0];
    }
    cell.remarksLabel.text=[self.firstArray objectAtIndex:indexPath.row];
    return cell;
}
-(IBAction)addnewRemarks:(id)sender
{
    [self.firstArray addObject:@""];
    NSInteger row = [self.firstArray count]-1;
    NSInteger section = 0;
    NSIndexPath *myindexpath = [NSIndexPath indexPathForRow:row inSection:section];
    // [selectedarray addObject:myindexpath];
    [self.firstTableView beginUpdates];

    [self.firstTableView insertRowsAtIndexPaths:@[myindexpath] withRowAnimation:UITableViewRowAnimationTop];
    [self.firstTableView endUpdates];
}

Upvotes: 1

Views: 41

Answers (1)

Akhilrajtr
Akhilrajtr

Reputation: 5182

instead of [self.firstArray addObject:@""]; use

[self.firstArray insertObject:@"" atIndex:0];

and in addnewRemarks: action set

NSInteger row = 0; 

to show the new row in top of the table.

so finally addnewRemarks method will be

-(IBAction)addnewRemarks:(id)sender
{
    NSInteger row = 0;
    NSInteger section = 0;
    [self.firstArray insertObject:@"" atIndex:row];
    NSIndexPath *myindexpath = [NSIndexPath indexPathForRow:row inSection:section];
    // [selectedarray addObject:myindexpath];
    [self.firstTableView beginUpdates];

    [self.firstTableView insertRowsAtIndexPaths:@[myindexpath] withRowAnimation:UITableViewRowAnimationTop];
    [self.firstTableView endUpdates];
}

in your code NSInteger row = [self.firstArray count]-1; which means the new item will be added at last index.

Upvotes: 2

Related Questions