2015-04-04 14 views
0

我想在內置動畫完成後執行一些代碼。如何在不使用完成塊的情況下在動畫之後執行代碼?

我有一個很多單元格/行的UITableView。有時候,當我做一些操作,然後我需要滾動到我的tableView的頂部。對於我使用:

tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true) 

但我需要執行一些代碼,一旦頂部到達,這樣一個簡單的選擇和1RST行取消。

我從UIScrollViewDelegate執行func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView)。它工作正常(或多或少,有時動畫不是很順利,我們看不到選擇/取消選擇「動畫」),除非我已經在tableView的頂部,那麼不會調用scrollViewDidEndScrollingAnimation

那麼有沒有一種方法可以執行一次代碼scrollToRowAtIndexPath:atScrollPosition:animated被調用?

編輯:

當我在談論做一些操作,我說的是從UITableView移動使用moveRowAtIndexPath:toIndexPath一行。

所以當需要滾動的時候它很好,兩個動畫都需要大約相同的時間。但是當不需要滾動時,然後執行我想在動畫之後執行的代碼,在動畫的同時開始執行

+0

您是否嘗試過把您的文章動畫代碼爲scrollViewDidEndDragging()和/或scrollViewDidEndDecelerating()? – Abdullah 2015-04-04 04:19:19

+0

是的,我嘗試了他們兩個,他們沒有在我的情況下調用,因爲它是一個動畫 – Nico 2015-04-04 04:49:57

回答

2

您可以使用我從an old Objective-C answer改編的這個Swift代碼來滾動視圖。

// First, test whether the tableView needs to scroll to the new position 
var originalOffset = tableView.contentOffset.y; 
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false) 

var offset = tableView.contentOffset.y; 

if (originalOffset == offset) { 
    // No animation is needed since its already there 
    doThingAfterAnimation(); 
} else { 
    // We know it will scroll to a new position 
    // Return to originalOffset. animated:NO is important 
    tableView.setContentOffset(CGPointMake(0, originalOffset), animated: false); 
    // Do the scroll with animation so `scrollViewDidEndScrollingAnimation:` will execute 
    tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true) 
} 

然後當然是:

func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { 
    doThingAfterAnimation(); 
} 
+0

我編輯的問題,以添加更多的信息,使我的問題的標題更有意義。在這種情況下,很好地檢測到需要滾動,但是當我不必滾動時,「doThingAfterAnimation」開始於動畫移動我的行的同時,我正在查找它以在動畫完成時開始。 – Nico 2015-04-04 05:00:56

+1

如果您正在嘗試同時移動單元格,那麼您需要使用其中一種方法爲這些動畫添加完成塊[here](http://stackoverflow.com/questions/3832474/uitableview- row-animation-duration-and-completion-callback),並且確保在繼續執行「doThingAfterAnimation」之前調用了「scrollViewDidEndScrollingAnimation」函數和你的單元格移動動畫的完成塊。我_思考_他們總是相同的動畫持續時間,所以你可能不需要太多協調...... – 2015-04-04 05:11:55

+0

感謝它的工作! – Nico 2015-04-04 07:47:05

相關問題