Animating a UIView to slide down, then slide up

Stonep123 picture Stonep123 · Dec 11, 2013 · Viewed 31.4k times · Source

Im trying to figure out why this isnt working

in my tableViewcontroller viewDidLoad

self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 5, 320,0)];

self.headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 320, 0)];

self.headerLabel.textAlignment = NSTextAlignmentCenter;

self.headerLabel.text = @"text";

[self.view addSubview:self.headerView];


[self.headerView addSubview:self.headerLabel];




[UIView animateWithDuration:.5 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{

    self.headerLabel.frame = CGRectMake(0, 5, 320,15);
    self.headerView.frame  = CGRectMake(0, 5, 320,15);

} completion:^(BOOL finished) {

    [UIView animateWithDuration:.5 delay:2.0 options:UIViewAnimationOptionCurveEaseIn animations:^{

        self.headerLabel.frame = CGRectMake(0, 5, 320,0);
        self.headerView.frame  = CGRectMake(0, 5, 320,0);

    } completion:^(BOOL finished) {

    }];

}];

if I remove the slide back up part in the completion block of the first animate call It works. The view slides down correctly. However I cannot get it to shrink back up at all. When I include the slide up code in the completion block the view is not displayed at all on load and I dont know why and Im going insane

Answer

rdelmar picture rdelmar · Dec 12, 2013

I'm not sure why the label disappears, but you can fix that by giving the view and label an appropriate height when you create them, and only animate the label's y position rather than its height.

- (void)viewDidLoad {
    [super viewDidLoad];

    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, -30, 320,30)];
    self.headerView.backgroundColor = [UIColor yellowColor];
    self.headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 320, 21)];

    self.headerLabel.textAlignment = NSTextAlignmentCenter;

    self.headerLabel.text = @"text";

    [self.view addSubview:self.headerView];
    [self.headerView addSubview:self.headerLabel];

    [UIView animateWithDuration:.5 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.headerView.frame  = CGRectMake(0, 0, 320,30);
    } completion:^(BOOL finished) {

        [UIView animateWithDuration:.5 delay:2.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            self.headerView.frame  = CGRectMake(0, -30, 320,30);

        } completion:^(BOOL finished) {

        }];

    }];
}