Code cracker
Code cracker

Reputation: 3166

How to change alpha value along with scrolling

I could not found any where for this kind sticky issue.My issue is when the user started scrolling i need to change the alpha value.At starting of scrolling alpha value should be 1, then at middle of scrolling alpha value should be 0.5, at end it must be 0.This what i need to do.i could not find with googling. help me plz

Upvotes: 4

Views: 6468

Answers (2)

Osama Remlawi
Osama Remlawi

Reputation: 2990

Here is how to do it in Swift, i have 2 UILabel in my controller, and i need to increase alpha for the first UILabel and decrease alpha for the second :

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
        // Bottom
        
    }

    if (scrollView.contentOffset.y < 0){
        // Top
        
        lblTitleHeader.alpha = 0
        
        lblTitleBody.alpha = 1
        
    }

    if (scrollView.contentOffset.y >= 0 && scrollView.contentOffset.y < (scrollView.contentSize.height - scrollView.frame.size.height)){
        // Middle
        
        let percentage: CGFloat = (scrollView.contentOffset.y) / 20
        
        // This label loses alpha when you scroll down (or slide up)
        lblTitleHeader.alpha = (percentage) 
        

        // This label gets more alpha when you scroll up (or slide down)
        lblTitleBody.alpha = (1 - percentage) 
        
        
        
    }
    
}

Upvotes: 1

cutsoy
cutsoy

Reputation: 10251

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    /* This is the offset at the bottom of the scroll view. */
    CGFloat totalScroll = scrollView.contentSize.height - scrollView.bounds.size.height;

    /* This is the current offset. */
    CGFloat offset = - scrollView.contentOffset.y;

    /* This is the percentage of the current offset / bottom offset. */
    CGFloat percentage = offset / totalScroll;

    /* When percentage = 0, the alpha should be 1 so we should flip the percentage. */
    scrollView.alpha = (1.f - percentage);
}

Upvotes: 28

Related Questions