lunes, 2 de mayo de 2016

iOS: Constraint animation

I wanted to animate a floating bar.

- (void)viewDidLoad
{
[super viewDidLoad];

self.floatingBar.hidden = YES;
    for (NSLayoutConstraint* contraint in self.view.constraints) {
        if ([contraint.identifier isEqualToString:@"top"]) {
            contraint.constant = -65 - self.floatingBar.frame.size.height;
            break;
        }

    }

...
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    
    if (offset.y < 400*) {
        if (!self.floatingBar.hidden) {
            self.floatingBar.hidden = YES;
            for (NSLayoutConstraint* contraint in self.view.constraints) {
                if ([contraint.identifier isEqualToString:@"top"])** {
                    contraint.constant = -65*** - self.floatingBar.frame.size.height;
                    break;
                }
            }
        }
        
    } else if (offset.y > 400) {
        if (self.floatingBar.hidden) {
            self.floatingBar.hidden = NO;
            
            [self.view layoutIfNeeded];
            
            [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                
                for (NSLayoutConstraint* contraint in self.view.constraints) {
                    if ([contraint.identifier isEqualToString:@"top"]) {
                        contraint.constant = -65;
                        break;
                    }
                }
                
                [self.view layoutIfNeeded];
                
            } completion:^(BOOL finished) {
                
            }];
        }
    }
}

* 400 was my threshhold
** Name of my constraint (identifier I used in interface builder)
*** I wanted my bar to be at the top of the window (under status bar and navigation bar)

No hay comentarios:

Publicar un comentario