iOS简单实现顶部横幅通知

在当前ViewController弹出顶部通知栏


效果图.gif
思路

没有思路, 画一个View,加两个动画一个延时

实现

.h文件

//
//  ELTopBannerNotificationsUtils.h
//  homework
//
//  Created by eleven on 2018/4/12.
//  Copyright © 2018年 homework. All rights reserved.
//

#import 

@interface ELTopBannerNotificationsUtils : NSObject

/**
 顶部横幅弹窗

 @param message NSString 弹窗内容
 */
+ (void)alertWithMessage:(NSString *)message, ...;

@end

.m文件

//
//  ELTopBannerNotificationsUtils.m
//  homework
//
//  Created by eleven on 2018/4/12.
//  Copyright © 2018年 homework. All rights reserved.
//

#import "ELTopBannerNotificationsUtils.h"
#import "ELControllerUtils.h"

#define kDefaultLastTime 1.4
#define kDefaultAnimationTime 0.3


@implementation HWTopBannerNotificationsUtils

+ (void)alertWithMessage:(NSString *)message
{
    if ([message isEqualToString:@""] || message == nil) {
        return;
    }

    CGFloat statusBarHeight = 10;
    if ([UIApplication sharedApplication].isStatusBarHidden || IS_IPHONE_X) {
        statusBarHeight = 0;
    }
    UIViewController *vc = [ELControllerUtils topViewController];
    __block UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, - 56 - HEIGHT_IPHONEX_BOTTOM_WHITE, ScreenWidth, 56 + HEIGHT_IPHONEX_BOTTOM_WHITE);
    view.backgroundColor = [UIColor whiteColor];
    if (vc.navigationController.navigationBarHidden) {
        [vc.view addSubview:view];
    } else {
        [vc.navigationController.navigationBar.superview addSubview:view];
    }
    
    UILabel *lab = [[UILabel alloc] init];
    lab.frame = CGRectMake(0, statusBarHeight + HEIGHT_IPHONEX_BOTTOM_WHITE, ScreenWidth, 56);
    lab.backgroundColor = [UIColor whiteColor];
    lab.text = message;
    lab.textAlignment = NSTextAlignmentCenter;
    lab.textColor = UIColorFromRGB(0x666666);
    lab.font = [UIFont systemFontOfSize:13];
    [view addSubview:lab];
    
    [UIView animateWithDuration:kDefaultAnimationTime delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        view.frame = CGRectMake(0, 0, ScreenWidth, 56 + HEIGHT_IPHONEX_BOTTOM_WHITE);
    } completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kDefaultLastTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:kDefaultAnimationTime delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                view.frame = CGRectMake(0, - 56 - HEIGHT_IPHONEX_BOTTOM_WHITE, ScreenWidth, 56 + HEIGHT_IPHONEX_BOTTOM_WHITE);
            } completion:^(BOOL finished) {
                [view removeFromSuperview];
                view = nil;
            }];
        });
    }];
}

@end

[ELControllerUtils topViewController]获取当前ViewController 参考链接点击

HEIGHT_IPHONEX_BOTTOM_WHITE为了适配iPhone X

你可能感兴趣的:(iOS简单实现顶部横幅通知)