Make background color change during scroll

前端 未结 5 1888
太阳男子
太阳男子 2021-01-14 07:10

I have an onboarding section of my app with 4 pages the users scrolls through horizontally to get an idea of how to use the app (standard). I want the background color to tr

5条回答
  •  被撕碎了的回忆
    2021-01-14 07:51

    To enable paging in scrollview you have to enable the paging property of scrollview first from attribute inspector.

    As per your requirement you have 4 pages. so your scrollview content size will be like scrollviewWidth * 4

    Put this code in viewDidLoad

    [self.scrollVw setContentSize:CGSizeMake(self.scrollVw.frame.size.width * 4,0)];
    

    Then take an array to store color values something like below.

     arrColor = [[NSMutableArray alloc]init];
    
     [arrColor addObject:[UIColor colorWithRed:(241.0f/255.0f) green:(170.0f/255.0f) blue:(170.0f/255.0f) alpha:1.0f]];
    
     [arrColor addObject:[UIColor colorWithRed:(170.0f/255.0f) green:(201.0f/255.0f) blue:(241/255.0f) alpha:1.0f]];
     [arrColor addObject:[UIColor colorWithRed:(188.0f/255.0f) green:(170.0f/255.0f) blue:(241.0f/255.0f) alpha:1.0f]];
     [arrColor addObject:[UIColor colorWithRed:(241.0f/255.0f) green:(199.0f/255.0f) blue:(170.0f/255.0f) alpha:1.0f]];
    
     [self.scrollVw setBackgroundColor:[arrColor objectAtIndex:0]]; //this is for first time to display first color when scrollview is load. you can avoid this by directly setting color from UI
    

    Scrollview delegate method code.

    -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
    {
     [self.scrollVw setBackgroundColor:[arrColor objectAtIndex:currentPage]]; //currentPage overhere is simple int variable which i had incremented and decremented its values based on current offset of scrollview. Also currentPage value should not be > 4.
    }
    

    Hope this will help you out. Happy coding :)

提交回复
热议问题