2015-11-03 6 views
1

Я хочу добавить ячейки в нижней части UITableView и прокрутить, чтобы сделать ее полностью видимой (как и в Whatsapp при отправке или получении сообщения).Добавить ячейку внизу и прокрутить UITableView

Я попытался сделать это:

[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:[self.tableView numberOfRowsInSection:0]-1 inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

Но это делает графический глюк и вспышку таблицы и сделать плохую прокрутку вместо гладких один.

Любая помощь?

+2

Я не в состоянии сказать с уверенностью, но вполне возможно, что на самом деле WhatsApp прокручивается в верхней части Tableview (0, 0). Это трюк, используемый некоторыми приложениями для обмена сообщениями для поворота таблицыView, а затем вращения каждой ячейки на 180 градусов. Это дает визуальное представление прокрутки вниз, но программный вид прокрутки вверх. – Avi

+1

Изменение анимированного: ДА для анимированного: НЕТ – Subash

+0

Предложение Субаша работает. Вы не можете оживить оба вызова. – Dave

ответ

0

пример функции для добавления элемента:

- (IBAction)addItem:(UIBarButtonItem *)sender { 
    [self.items addObject:[NSString stringWithFormat:@"Item %lu", self.items.count + 1]]; 

    NSIndexPath *indexPathToInsert = [NSIndexPath indexPathForRow:self.items.count - 1 inSection:0]; 
    [self.tableView insertRowsAtIndexPaths:@[indexPathToInsert] withRowAnimation:UITableViewRowAnimationAutomatic]; 
    [self.tableView scrollToRowAtIndexPath:indexPathToInsert atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
} 

для меня анимация выглядит прекрасно таким образом!

+0

Я пробовал, но весь просмотр таблицы прокручивается во время мигания ... Спасибо за ответ в любом случае – facumedica

0

Ну, что я сделал, это использовать [self.tableView scrollToRowAtIndexPath..., но называя его 0.1s NSTimer.

2

здесь то, что я сделал это, вставить строку, а затем изменили врезку содержания Tableview

-(IBOutlet)sendButton:(id)sender 
{ 
    [array addObject:textView.text]; 
    [self addAnotherRow]; 
} 
- (void)addAnotherRow { 
     NSIndexPath *indexPath = [NSIndexPath indexPathForItem:(array.count - 1) inSection:0]; 
     [self.messagesTableView beginUpdates]; 
     [self.messagesTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
     [self.messagesTableView endUpdates]; 
     [self updateContentInsetForTableView:self.messagesTableView animated:YES]; 

     // TODO: if the scroll offset was at the bottom it can be scrolled down (allow user to scroll up and not override them) 

     [self.messagesTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
} 

- (void)updateContentInsetForTableView:(UITableView *)tableView animated:(BOOL)animated { 
    NSUInteger lastRow = [self tableView:tableView numberOfRowsInSection:0]; 
    NSLog(@"last row: %lu", (unsigned long)lastRow); 
    NSLog(@"items count: %lu", (unsigned long)array.count); 

    NSUInteger lastIndex = lastRow > 0 ? lastRow - 1 : 0; 

    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:lastIndex inSection:0]; 
    CGRect lastCellFrame = [self.messagesTableView rectForRowAtIndexPath:lastIndexPath]; 

    // top inset = table view height - top position of last cell - last cell height 
    CGFloat topInset = MAX(CGRectGetHeight(self.messagesTableView.frame) - lastCellFrame.origin.y - CGRectGetHeight(lastCellFrame), 0); 

    // What about this way? (Did not work when tested) 
    // CGFloat topInset = MAX(CGRectGetHeight(self.tableView.frame) - self.tableView.contentSize.height, 0); 

    NSLog(@"top inset: %f", topInset); 

    UIEdgeInsets contentInset = tableView.contentInset; 
    contentInset.top = topInset; 
    NSLog(@"inset: %f, %f : %f, %f", contentInset.top, contentInset.bottom, contentInset.left, contentInset.right); 

    NSLog(@"table height: %f", CGRectGetHeight(self.messagesTableView.frame)); 

    UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState; 
    [UIView animateWithDuration:animated ? 0.25 : 0.0 delay:0.0 options:options animations:^{ 
     tableView.contentInset = contentInset; 

    } completion:^(BOOL finished) { 
    }]; 
} 

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

- (void)viewDidLayoutSubviews { 
    [self updateContentInsetForTableView:self.messagesTableView animated:NO]; 
} 
1

сделать вставки анимированных и после endUpdates прокрутки дна не анимировать. Работал для меня

Swift

self.tableView.beginUpdates() 
self.tableView.insertRowsAtIndexPaths(newIndexPaths, withRowAnimation: UITableViewRowAnimation.Top) 
self.tableView.endUpdates() 
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: self.tableDataCount-1, inSection: 0), atScrollPosition: .Bottom, animated: false) 
Смежные вопросы