Как вставить строку во время выполнения в UITableView на iPhone? - PullRequest
1 голос
/ 31 января 2012

Я создал одну кнопку с действием, чтобы добавить строку к UITableView во время выполнения, но мой код не работает.Я вижу анимацию строки внизу, но она отображается только в том случае, если моя строка UITableView не добавлена.Что я могу сделать в этом коде, чтобы увидеть строку, добавленную в ячейку?

У меня есть 4 раздела, и я хочу добавить строку для 1 раздела в строке 0 и 2 раздела в строке 0:

-(IBAction)add:(id)sender
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NSArray* path = [NSArray arrayWithObject:indexPath];

    // fill paths of insertion rows here
    [self.mytableview beginUpdates];
    [self.mytableview insertRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationBottom];      
    [self.mytableview deleteRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationBottom];
    [self.mytableview endUpdates];
    [self.mytableview reloadData];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger rows;
    if (section==0) {
        rows = 4;
        //return    rowForSectionOne;
        //rows=rowForSectionOne++;
    }
    if (section == 1) 
    {
        rows = 1;
    }

    return rows;        
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [mytableview dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }

    if ([indexPath row] == 0 && [indexPath section] == 0)
    {
        cell.textLabel.text=@"Title";

        cell.accessoryView = textField;
        titlename=textField.text;
        [[cell imageView] setImage:[UIImage imageNamed:@"DetailViewDue.png"]];
        NSLog(@"******:%@",titlename);          
    }

    if ([indexPath row] == 1 && [indexPath section] == 0)
    {
        cell.textLabel.text=@"Tags";
        cell.detailTextLabel.text=app.Tags;
     [[cell imageView] setImage:[UIImage imageNamed:@"DetailViewTag.png"]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    if ([indexPath row] == 2 && [indexPath section] == 0)
    {
        cell.textLabel.text=@"Notes";
        cell.detailTextLabel.text=app.Notes;
        [[cell imageView] setImage:[UIImage imageNamed:@"DetailViewNote.png"]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd/MM/yyyy"];
    fromDate = [[dateFormat stringFromDate:selectionData.fromDateSelected]retain];

    if ([indexPath row] == 3 && [indexPath section] == 0)
    {
        cell.textLabel.text=@"DueDate";
        cell.detailTextLabel.text=fromDate;
        [[cell imageView] setImage:[UIImage imageNamed:@"DetailViewDue.png"]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }
    if ([indexPath row] == 0 && [indexPath section] == 1)
    {
        cell.textLabel.text=@"Attach";

    }

    return cell;
}

Ответы [ 2 ]

1 голос
/ 31 января 2012

Вам нужно всего лишь добавить несколько строк кода в методе "cellForRowAtIndexPath"

   if(cell ==nil)
      {
        cell =[[UITableViewAlloc alloc]initWithStyle.... ]
      }
   int theRow = indexPath.row;
   if(indexPath.section  == 1) theRow += 3;
   if(indexPath.section  == 2) theRow += 5;
   if(indexPath.section  == 3) theRow += 4;
   if(indexPath.section  == 4) theRow += 3;

  //load the view in it

  cell.textLable . text = [<your object> objectAtIndexPath.row];
 return cell;

  Here you can add rows as many as you want....
1 голос
/ 31 января 2012

Ну, вы делаете все правильно.Скажем, при нажатии кнопки вызывается -(IBAction)add:(id)sender.затем составьте indexPath с соответствующими row & section.Здесь раздел равен 0,1,2,3 (поскольку у вас есть 4 раздела -

NSIndexPath *indexPath0 = [NSIndexPath indexPathForRow:0 inSection:0];
NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:0 inSection:1];
NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:0 inSection:2];
NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:0 inSection:3];    
//put these indexpaths in a NSArray

[tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone];

Это должно обновить таблицу. Нет необходимости делать reloadData для таблицы, так как вы добавляете только одну строку (& не изменяя всю таблицу.) Также убедитесь, что dataSource имеет эту новую добавленную запись для каждого раздела, в противном случае ваше приложение вылетит

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...