2016-07-11 50 views
0

我正在使用UITableView構建聊天界面。我使用下面的代碼如何添加最後一行到UITableView平滑滾動?

self.tableView.beginUpdates() 
self.tableView.insertRows(at: [IndexPath(row: self.messageCards.count - 1, section: 0)], with: .bottom) 
    self.tableView.endUpdates() 

添加單元格和我使用scrollToRowAtIndexPath顯示最後插入的行後添加。

let indexPath = IndexPath(row: self.messageCards.count - 1, section: 0) 
self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) 

但最後兩個動畫混合和滾動不順利發生。

+0

應該是什麼的期望的順序動畫.. –

+0

@RohitKP首先我想向上滾動,並想使用動畫顯示新消息 –

回答

0

你可以試試這個,我已經測試代碼:

arrayData.addObject(str) 
    let indexpath = NSIndexPath(forRow: arrayData.count-1, inSection: 0) 

    tblView.insertRowsAtIndexPaths([indexpath], withRowAnimation: UITableViewRowAnimation.Automatic) 
    tblView.scrollToRowAtIndexPath(indexpath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true) 

以下是輸出:讓我知道如果你想要完整的源代碼。

enter image description here

0

請看看這個。

[UITableView animateWithDuration:5.0 delay:0.1 options:UIViewAnimationOptionCurveEaseOut animations:^{ 
     [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messageCards.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade]; 
    } completion:^(BOOL finished) { 
     NSLog(@"animated"); 
     [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathWithIndex:self.messageCards.count-1] atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
    }]; 
0
You can implement below code. its working fine. 

[self.messageCards addObject:@"DATA Whatever you want"]; 
[self.tableView reloadData]; 
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageCards.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
0

它的奇蹟,但要實現平穩剛剛滾動時需要調用reloadData增加()

func fetchNext(_ countToFetch: Int? = 10) { 

    let existingCount = items?.count ?? 0 

    networkService?.items(bySkip: existingCount, take: countToFetch, completion: { (data, error) in 

     if let newItems = data?.items() as? [Element], newItems.count > 0 { 
      self.items?.append(contentsOf: newItems) 
      self.refreshCallback?() 
     } 
    }) 
} 

回調:

datasource?.refreshCallback = { [weak self] in 

    if #available(iOS 10.0, *) { 
     self?.table.refreshControl?.endRefreshing() 
    } 
    self?.table.reloadData() 
}