I've scrollview with page control and I want to make the subview of my scrollview fadeIn/fadeOut when I scroll to or from the next page. I found that I can use contentOffset to make this effect but I couldn't make it. In fact, I'm newbie and I wish If there is any tutorial that can help. thank you.
问问题
3903 次
4 回答
4
假设您在 self.viewControllers 中保存一组视图控制器,根据 UIPageControl 进行索引:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat diffFromCenter = ABS(scrollView.contentOffset.x - (self.pageControl.currentPage)*self.view.frame.size.width);
CGFloat currentPageAlpha = 1.0 - diffFromCenter/self.view.frame.size.width;
CGFloat sidePagesAlpha = diffFromCenter/self.view.frame.size.width;
//NSLog(@"%f",currentPageAlpha);
[[[self.viewControllers objectAtIndex:self.pageControl.currentPage] view] setAlpha:currentPageAlpha];
if (self.pageControl.currentPage > 0)
[[[self.viewControllers objectAtIndex:self.pageControl.currentPage-1] view] setAlpha:sidePagesAlpha];
if (self.pageControl.currentPage < [self.viewControllers count]-1)
[[[self.viewControllers objectAtIndex:self.pageControl.currentPage+1] view] setAlpha:sidePagesAlpha];
}
于 2014-10-26T13:36:39.180 回答
0
你可以看看这个关于视图动画的教程:
uiview-tutorial-for-ios-how-to-use-uiview-animation
为了达到你正在寻找的效果,你可以使用这样的东西:
用于检测滚动的 ScrollView 委托方法(如果您只有分页)
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
UIView* subView = [scrollView.subviews lastObject]; //Or however you access your subview
[UIView animateWithDuration:1.0f animations:^{
subView.alpha = 0.0f;
} completion:^(BOOL finished){
[UIView animateWithDuration:1.0f animations:^{
subView.alpha = 1.0f;
}];
}];
}
这将导致您的子视图在 2.0 秒内平滑淡出和淡入。您应该阅读一下有关此动画块的信息,因为它们可能有点棘手。例如,我在第一个动画块完成后嵌套了第二个动画块,因为它们中的实际代码会立即处理,并且动画只是发生在事物的视图端。
希望这可以帮助!
于 2013-09-15T18:19:11.220 回答
0
您可以将其淡化为零,更改contentOffset
无动画,然后使用 1.0 将其淡化回 alpha:
- (IBAction)didChangePageView:(id)sender
{
[UIView animateWithDuration:0.25
animations:^{
self.scrollView.alpha = 0.0;
}
completion:^(BOOL finished) {
[self.scrollView setContentOffset:CGPointMake(0, self.scrollView.frame.size.height * self.pageViewControl.currentPage) animated:NO];
[UIView animateWithDuration:0.25 animations:^{
self.scrollView.alpha = 1.0;
}];
}];
}
于 2013-09-15T19:17:47.703 回答
0
使用 Swift 2.0,假设您在 myViewsArray 中保存了一个子视图数组:
func scrollViewDidScroll(scrollView: UIScrollView) {
//Fade in/out effect while scrolling
for (index,subView) in myViewsArray.enumerate() {
label.alpha = 1 - abs(abs(scrollView.contentOffset.x) - subView.frame.width * CGFloat(index)) / subView.frame.width
}
}
于 2016-03-14T08:31:26.517 回答