animation完成后执行任务(在iOS中)

所以我有这样的代码行:

[tableView setContentOffset:point animated:YES];

我想在animation结束后再运行一段代码。 我的尝试是将animation代码(setContentOffset)放在一个单独的方法中,并使用下面的代码调用它:

[self performSelectorOnMainThread:@selector(scrollMethod:) withObject:sender waitUntilDone:YES];

问题是该方法立即返回,而不是在animation完成后,即使waitUntilDone为YES,但显然这是animation的工作原理。

我知道我可以使用线程等待,但它不干净,所以我只会用它作为最后的手段。 (也许我会用这个,如果我知道滚动animation发生的时间。)

任何想法如何去做这个是受欢迎的。

(PS的场景是这样的:我显示了一个popup窗口,当没有键盘时显示完美,但是,如果键盘是可见的,popup窗口的高度会缩小,有时会减less到几乎边界。 ,我想向上滚动视图,以便popover永远不会popup键盘。)

尝试使用这种方法:

 [UIView animateWithDuration:0.6f delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{ // Do your animations here. } completion:^(BOOL finished){ if (finished) { // Do your method here after your animation. } }]; 

UITableView从其超类UIScrollViewinheritancesetContentOffset:animated:。 查看UIScrollViewDelegate的scrollViewDidEndScrollingAnimation:方法。

对于scrollView,tableView或collectionView,如果你这样做:

 [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x+260.0, self.collectionView.contentOffset.y) animated:YES]; 

那么你会得到一个:

 -(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView 

当滚动完成。

如果用户移动视图,则不会获得此callback。

您可以创buildanimation并直接告诉它们在完成后执行一个块。

这里有一个替代scheme,可以用UITableView的animation效果更好。

 [UIView beginAnimations:nil context:sender]; [UIView setDelegate:self]; [UIView setDidStopSelector:@selector(scrollMethod:)]; [tableView setContentOffset:point]; [UIView commitAnimations]; 

并确保实现您的scrollMethod:与此签名:

 - (void)scrollMethod:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context 

您可以使用上下文来了解您拥有哪个sender 。 有关UIViewanimation的更多信息,请阅读UIView文档 。