我有 UITableView 的 View 。在此列表上方,我有 UIButton。我需要实现一个动画,该动画将根据列表上的滚动垂直移动按钮并在滚动完成后返回基本位置。我在下面的图片中显示向下滚动:
现在我检测开始和停止滚动列表事件并做这样的动画:
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGRect newFrame = button.frame;
newFrame.origin.y = screenHeight - (newFrame.size.height/2.0);
[UIView animateWithDuration:2
animations:^{
button.frame = newFrame;
}];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGRect newFrame = storedButtonFrame;
[UIView animateWithDuration:2
animations:^{
button.frame = newFrame;
}];
}
我对此几乎没有问题首先是,当我向下滚动时,我的动画正在制作动画然后结束,我想根据滚动列表制作动画,例如。当我向下滚动列表 10 像素时,我只想将 10 像素的按钮移动到列表的末尾。其次,当开始滚动动画仍在运行时,我得到停止滚动事件,开始动画闪烁到结束,结束动画开始动画,这绝对是我不想要的。我在 iOS 方面没有太多经验,我真的不知道该怎么做。知道我该怎么做这样的事情吗?
最佳答案
而不是使用 scrollViewWillBeginDragging:
你可以使用 scrollViewDidScroll:
像这样:
/// Animate the button position as the scroll view scrolls
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat percentage = scrollView.contentOffset.y / scrollView.contentSize.height;
CGRect frame = _button.frame;
frame.origin.y = scrollView.contentOffset.y + percentage * self.tableView.frame.size.height;
_button.frame = frame;
}
/// Animate the button back to the top-right corner
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGRect frame = _button.frame;
frame.origin.y = scrollView.contentOffset.y;
[UIView animateWithDuration:0.4f
animations:^{
_button.frame = frame;
}];
}
这使按钮在您滚动列表时跟随滚动指示器。
scrollViewDidScroll:
经常触发,因此运动平稳。当列表停止时,它会回到右上角的默认位置,您可以从
contentOffset.y
获得.
关于滚动列表时的iOS动画按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22360908/