江戸一番のジャスタウェイ職人のブログ

江戸一番のジャスタウェイ職人

タイムラインの自動スクロールを自然な動きにする(UITableView)

UITableViewにはinsertRowsAtIndexPathsというセルをアニメーションさせながら追加できる便利なメソッドがあり、そのアニメーションオプション(withRowAnimation)を使っていたんですが、これはTwitterクライアントのタイムラインとしては一般的ではない動きをしていています。(個人の感想です)

withRowAnimationに他に良いパターンがないかとか調べたんですが、普通にアニメーションなしで追加したあとにsetContentOffset:CGPointZero animated:YESするといい感じになりました。

f:id:s-aska:20140604221506p:plain

※上の図は修正前、下の図は修正後(下記コードは実装例)

// スクロール位置が画面一番上の時だけ自動スクロールする
BOOL autoScroll = self.tableView.contentOffset.y > 0 && [self.tableView.visibleCells count] > 0 ? NO : YES;

// 画面を動かさずにセルを追加する
UITableViewCell *lastCell = [self.tableView.visibleCells lastObject];
CGFloat offset = lastCell.frame.origin.y - self.tableView.contentOffset.y;
[UIView setAnimationsEnabled:NO];
// withRowAnimation:UITableViewRowAnimationBottomは不自然なのでしない
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
[self.tableView setContentOffset:CGPointMake(0.0, lastCell.frame.origin.y - offset) animated:NO];
[UIView setAnimationsEnabled:YES];

// 自動スクロール
if (autoScroll) {
    [self.tableView setContentOffset:CGPointZero animated:YES];
}

https://github.com/s-aska/Justaway-for-iOS/commit/c2a00a4d1fc4acffa354b261d3df8a98b182b848