как правильно использовать insertRowsAtIndexPaths? - PullRequest
33 голосов
/ 04 августа 2011

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

Мой метод «add» делает это:

- (IBAction) toggleEnabledTextForSwitch1onSomeLabel: (id) sender {  
if (switch1.on) {

    NSArray *appleComputers = [NSArray arrayWithObjects:@"WWWWW" ,@"XXXX", @"YYYY", @"ZZZZ", nil];
    NSDictionary *appleComputersDict = [NSDictionary dictionaryWithObject:appleComputers forKey:@"Computers"];
    [listOfItems replaceObjectAtIndex:0 withObject:appleComputersDict];
    [tblSimpleTable reloadData];

}

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

Моя последняя попытка была сделана так:

- (IBAction) toggleEnabledTextForSwitch1onSomeLabel: (id) sender {  
if (switch1.on) {

    NSIndexPath *path1 = [NSIndexPath indexPathForRow:1 inSection:0]; //ALSO TRIED WITH indexPathRow:0
      NSArray *indexArray = [NSArray arrayWithObjects:path1,nil];   
     [tblSimpleTable insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationRight];

}
}  

Что я делаю не так? Как я могу сделать это легко? Я не понимаю всей этой вещи indexPathForRow ... Я также не понимаю, как с помощью этого метода я могу добавить имя метки в новую ячейку. Пожалуйста, помогите ... спасибо !!

Ответы [ 5 ]

23 голосов
/ 04 августа 2011

Это двухэтапный процесс:

Сначала обновите источник данных, чтобы numberOfRowsInSection и cellForRowAtIndexPath вернули правильные значения для ваших данных после вставки. Вы должны сделать это перед тем, как вставлять или удалять строки, иначе вы увидите ошибку «неверное количество строк».

Затем вставьте строку:

[tblSimpleTable beginUpdates];
[tblSimpleTable insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationRight];
[tblSimpleTable endUpdates];

Простая вставка или удаление строки не меняет ваш источник данных; ты должен сделать это сам.

22 голосов
/ 04 августа 2011

При использовании insertRowsAtIndexPaths важно помнить, что ваш UITableViewDataSource должен соответствовать тому, что говорит вставка. Если вы добавляете строку в табличное представление, убедитесь, что данные основы уже обновлены для соответствия.

6 голосов
/ 04 августа 2011

Прежде всего, вы должны обновить модель данных непосредственно перед обновлением самой таблицы.Также вы можете использовать:

[tableView beginUpdates];
// do all row insertion/delete here
[tableView endUpdates];

И таблица будет производить все измененные сразу с анимацией (если вы укажете это)

2 голосов
/ 11 сентября 2015

insertRowsAtIndexPaths:withRowAnimation: И изменения в вашей модели данных оба должны произойти в промежутке между beginUpdates и endUpates

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

@interface MyTableViewController ()
@property (nonatomic, strong) NSMutableArray *expandableArray;
@property (nonatomic, strong) NSMutableArray *indexPaths;
@property (nonatomic, strong) UITableView *myTableView;
@end

@implementation MyTableViewController

- (void)viewDidLoad
{
    [self setupArray];
}

- (void)setupArray
{
    self.expandableArray = @[@"One", @"Two", @"Three", @"Four", @"Five"].mutableCopy;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.expandableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //here you should create a cell that displays information from self.expandableArray, and return it
}

//call this method if your button/cell/whatever is tapped
- (void)didTapTriggerToChangeTableView
{
    if (/*some condition occurs that makes you want to expand the tableView*/) {
        [self expandArray]
    }else if (/*some other condition occurs that makes you want to retract the tableView*/){
        [self retractArray]
    }
}

//this example adds 1 item
- (void)expandArray
{
    //create an array of indexPaths
    self.indexPaths = [[NSMutableArray alloc] init];
    for (int i = theFirstIndexWhereYouWantToInsertYourAdditionalCells; i < theTotalNumberOfAdditionalCellsToInsert + theFirstIndexWhereYouWantToInsertYourAdditionalCells; i++) {
        [self.indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    }

    //modify your array AND call insertRowsAtIndexPaths:withRowAnimation: INBETWEEN beginUpdates and endUpdates
    [self.myTableView beginUpdates];
    //HERE IS WHERE YOU NEED TO ALTER self.expandableArray to have the additional/new data values, eg:
    [self.expandableArray addObject:@"Six"];
    [self.myTableView insertRowsAtIndexPaths:self.indexPaths withRowAnimation:(UITableViewRowAnimationFade)];  //or a rowAnimation of your choice

    [self.myTableView endUpdates];
}

//this example removes all but the first 3 items
- (void)retractArray
{
    NSRange range;
    range.location = 3;
    range.length = self.expandableArray.count - 3;

    //modify your array AND call insertRowsAtIndexPaths:withRowAnimation: INBETWEEN beginUpdates and endUpdates
    [self.myTableView beginUpdates];
    [self.expandableArray removeObjectsInRange:range];
    [self.myTableView deleteRowsAtIndexPaths:self.indexPaths withRowAnimation:UITableViewRowAnimationFade];  //or a rowAnimation of your choice
    [self.myTableView endUpdates];
}

@end
0 голосов
/ 24 апреля 2015

Для быстрых пользователей

// have inserted new item into data source

// update
self.tableView.beginUpdates()
var ip = NSIndexPath(forRow:find(self.yourDataSource, theNewObject)!, inSection: 0)
self.tableView.insertRowsAtIndexPaths([ip], withRowAnimation: UITableViewRowAnimation.Fade)
self.tableView.endUpdates()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...