利用"animateWithDuration"實現帶彈簧動畫的頂部通知欄

看到其他App上有帶彈簧動畫的頂部通知欄,於是研究了實現方法,封裝了一下實現了效果,代碼如下:


PBFSpringEffectAlertView.h

//
//  PBFSpringEffectAlertView.h
//  BoyingCaptial
//
//  Created by BY-MAC01 on 16/1/6.
//  Copyright © 2016年 BY-MAC01. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol PBFSpringEffectAlertViewDatasource
//裝備View
- (void)assmebleViewTopBar:(UIView *)viewBackground;
@end

@interface PBFSpringEffectAlertView : UIView

- (instancetype)initWithSize:(CGSize)size;

@property (nonatomic,weak)id<PBFSpringEffectAlertViewDatasource>     datasource;

//彈出
- (void)show;
//彈回
- (void)hide;
@end



PBFSpringEffectAlertView.m

//
//  PBFSpringEffectAlertView.m
//  BoyingCaptial
//
//  Created by BY-MAC01 on 16/1/6.
//  Copyright © 2016年 BY-MAC01. All rights reserved.
//

#import "PBFSpringEffectAlertView.h"

@interface PBFSpringEffectAlertView()
//背景
@property (nonatomic,strong)UIView                  *VIEWBackground;
@end

@implementation PBFSpringEffectAlertView
- (instancetype)initWithSize:(CGSize)size{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    [self setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.7f]];
    
    //白色背景
    CGRect rect = [UIScreen mainScreen].bounds;
    self.VIEWBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0,size.width, size.height)];
    [self.VIEWBackground setBackgroundColor:[UIColor whiteColor]];
    [self.VIEWBackground.layer setCornerRadius:3.0f];
    self.VIEWBackground.center = CGPointMake(rect.size.width/2, rect.size.height/2);
    
    return self;
}

- (void)willMoveToSuperview:(UIView *)newSuperview{
    [self addSubview:self.VIEWBackground];
    if (self.datasource) {
        [self.datasource assmebleViewTopBar:self.VIEWBackground];
    }
}

//彈出
- (void)show{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    CGRect rect = [UIScreen mainScreen].bounds;
    CGRect rectBackground = self.VIEWBackground.frame;
    rectBackground.origin.y = -rectBackground.size.height;
    [self.VIEWBackground setFrame:rectBackground];
    [self.VIEWBackground setAlpha:0];
    [UIView animateWithDuration:0.7f delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:10 options:UIViewAnimationOptionCurveLinear animations:^{
        self.VIEWBackground.center = CGPointMake(rect.size.width/2, rect.size.height/2);
        [self.VIEWBackground setAlpha:1];
    } completion:^(BOOL finished) {
        [self hide];
    }];
}

//彈回
- (void)hide{
    [UIView animateWithDuration:0.3f animations:^{
        CGRect rectBackground = self.VIEWBackground.frame;
        rectBackground.origin.y = -rectBackground.size.height;
        [self.VIEWBackground setFrame:rectBackground];
        [self.VIEWBackground setAlpha:0];
    } completion:^(BOOL finished) {
        if([self superview]){
            [self removeFromSuperview];
        }
    }];

}

@end


效果如下:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章