Search code examples
iosuiscrollviewalphauiscrollviewdelegate

Using a UIScrollView to change the alpha of an image


My aim is to effectively use a UIScrollView as a UISlider.

I've managed to code a UISlider to change the alpha of an image however I want to code a scrollview to change the alpha of an image when it is scrolled.

I think I'm on the right lines by using the scroll views content offset to adjust alpha balances in the scroll view delegate but I just can't seem to get the code to work!

Any suggestions on how I can get do this?

Thanks


Solution

  • Yes, you have right... use the scroll view offset to modify the alpha:

    For example:

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView { 
    
        if(scrollView.contentOffset.y >= 0 && scrollView.contentOffset.y <= 150.0) {
            float percent = (scrollView.contentOffset.y / 150.0);
                   self.imageView.alpha = percent;
    
        } else if (scrollView.contentOffset.y > 150.0){
            self.imageView.alpha = 1;
    
        } else if (scrollView.contentOffset.y < 0) {
           // do other ... ;
        }
    }
    

    here you have an example: https://dl.dropboxusercontent.com/u/19438780/ScrollView_alpha.zip

    So... happy coding!