iOS-仿微信语音悬浮窗效果

演示

演示.gif

ps:实际上有一层较淡的阴影效果,gif中看不出来,可以根据需要自行调节阴影浓度。

悬浮层

LJKAudioCallAssistiveTouchView.h

#import <UIKit/UIKit.h>

@protocol LJKAudioCallAssistiveTouchViewDelegate <NSObject>

@optional

- (void)assistiveTouchViewClicked;

@end

@interface LJKAudioCallAssistiveTouchView : UIView
- (instancetype)initDefaultTypeWithBegainDate:(NSDate *)date;

+ (UIWindow *)getCurrentWindow;

@property (weak, nonatomic) id<LJKAudioCallAssistiveTouchViewDelegate> delegate;

@end

LJKAudioCallAssistiveTouchView.m

#import "LJKAudioCallAssistiveTouchView.h"
#define WIDTH self.frame.size.width
#define HEIGHT self.frame.size.height
#define kScreenWidth [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height
#define defaultHeight 80
#define leftAndRightSpace 12

@interface LJKAudioCallAssistiveTouchView ()
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) NSDate *begainDate;
@property (nonatomic)dispatch_source_t dispatchTimer;
@end

@implementation LJKAudioCallAssistiveTouchView

- (void)removeFromSuperview{
    [super removeFromSuperview];
    
    dispatch_source_cancel(self.dispatchTimer);
    self.dispatchTimer = nil;
    
}

- (instancetype)initDefaultTypeWithBegainDate:(NSDate *)date{
    if(self = [super init])
    {
        self.begainDate = date;
        self.backgroundColor = [UIColor clearColor];
        self.frame = CGRectMake(kScreenWidth - leftAndRightSpace - defaultHeight, [LJKAudioCallAssistiveTouchView iPhoneTopMargin] + 56, defaultHeight, defaultHeight);
        self.layer.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.06].CGColor;
        self.layer.shadowOffset = CGSizeMake(0,2);
        self.layer.shadowOpacity = 0.8;
        self.layer.shadowRadius = 5;
        
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, defaultHeight, defaultHeight)];
        backView.backgroundColor = [UIColor whiteColor];
        backView.layer.masksToBounds = YES;
        backView.layer.cornerRadius  = 8;
        [self addSubview:backView];
        
        _imageView = [[UIImageView alloc]initWithFrame:(CGRect){25, 16, 32, 32}];
        _imageView.image = [UIImage imageNamed:@"audioCall_voice_fold"];
        [backView addSubview:_imageView];
        
        _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 52, self.frame.size.width, 20)];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        [_timeLabel setFont:[UIFont systemFontOfSize:14]];
        [_timeLabel setTextColor:[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1]];
        _timeLabel.text = @"正在接通";
        [backView addSubview:_timeLabel];
        
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(locationChange:)];
        pan.delaysTouchesBegan = YES;
        [self addGestureRecognizer:pan];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click:)];
        [self addGestureRecognizer:tap];
        
        //开始计时的时机可以自行调节
        self.dispatchTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());

        dispatch_source_set_timer(self.dispatchTimer, DISPATCH_TIME_NOW, 1*NSEC_PER_SEC, 0*NSEC_PER_SEC);

        dispatch_source_set_event_handler(self.dispatchTimer, ^{
            [self getCurrentTimeLength];
        });

        dispatch_resume(self.dispatchTimer);
        
    }
    return self;
}

- (void)getCurrentTimeLength {

    NSTimeInterval lateTime = [self.begainDate timeIntervalSince1970];

    NSDate *currentDate = [NSDate date];
    NSTimeInterval currentTime = [currentDate timeIntervalSince1970];

    NSTimeInterval cha = currentTime - lateTime;

    int sec = (int) cha % 60;
    int min = (int) cha / 60 % 60;

    NSString *differTime = [NSString stringWithFormat:@"%02d:%02d",min,sec];
    
    self.timeLabel.text = differTime;
}

//改变位置
- (void)locationChange:(UIPanGestureRecognizer*)p
{

    CGPoint panPoint = [p locationInView:[LJKAudioCallAssistiveTouchView getCurrentWindow]];

    if(p.state == UIGestureRecognizerStateChanged)
    {
        self.center = CGPointMake(panPoint.x, panPoint.y);
    }
    else if(p.state == UIGestureRecognizerStateEnded)
    {
        CGFloat iPhoneTopMargin = [LJKAudioCallAssistiveTouchView iPhoneTopMargin];
        
        CGFloat iPhoneBottomMargin = [LJKAudioCallAssistiveTouchView iPhoneBottomMargin];
        
        if(panPoint.x <= kScreenWidth / 2)
        {
            if(panPoint.y < iPhoneTopMargin + HEIGHT / 2)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(WIDTH / 2 + leftAndRightSpace, iPhoneTopMargin + HEIGHT / 2);
                }];
            }
            else if(panPoint.y >= kScreenHeight - HEIGHT / 2 - iPhoneBottomMargin)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(WIDTH / 2 + leftAndRightSpace, kScreenHeight - HEIGHT / 2 - iPhoneBottomMargin);
                }];
            }
            else
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(WIDTH / 2 + leftAndRightSpace, panPoint.y);
                }];
            }
        }
        else if(panPoint.x > kScreenWidth / 2)
        {
            if(panPoint.y <= iPhoneTopMargin + HEIGHT / 2)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(kScreenWidth - WIDTH / 2 - leftAndRightSpace, iPhoneTopMargin + HEIGHT / 2);
                }];
            }
            else if(panPoint.y > kScreenHeight - HEIGHT / 2 - iPhoneBottomMargin)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(kScreenWidth - WIDTH / 2 - leftAndRightSpace, kScreenHeight - HEIGHT / 2 - iPhoneBottomMargin);
                }];
            }
            else
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(kScreenWidth - WIDTH / 2 - leftAndRightSpace, panPoint.y);
                }];
            }
        }
    }

}
//点击事件
-(void)click:(UITapGestureRecognizer*)t
{
    
    if ([self.delegate respondsToSelector:@selector(assistiveTouchViewClicked)]) {
        [self.delegate assistiveTouchViewClicked];
    }
}

+ (CGFloat)iPhoneTopMargin {
    if (@available(iOS 11.0, *)) {
        return [self getCurrentWindow].safeAreaInsets.top;
    } else {
        return 20;
    }
}

+ (CGFloat)iPhoneBottomMargin {
    if (@available(iOS 11.0, *)) {
        return [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom;
    } else {
        return 0;
    }
}

+ (UIWindow *)getCurrentWindow {
    __block UIWindow * window;
    
    if (@available(iOS 13.0, *)) {
        
        [[UIApplication sharedApplication].connectedScenes enumerateObjectsUsingBlock:^(UIScene * _Nonnull obj, BOOL * _Nonnull stop) {
            if (obj.activationState == UISceneActivationStateForegroundActive &&
                [obj isKindOfClass:UIWindowScene.self]) {
                UIWindowScene * windowScene = (UIWindowScene *)obj;
                NSArray<UIWindow *> * windows = windowScene.windows;
                for (UIWindow * win in windows) {
                    if ([win isKeyWindow]) {
                        window = win;
                        *stop = true;
                        break;
                    }
                }
            }
        }];
        
        if (window == nil) {
            NSArray<UIWindow *> * windows = [[UIApplication sharedApplication]windows];
            for (UIWindow * win in windows) {
                if ([win isKeyWindow]) {
                    window = win;
                    break;
                }
            }
        }
        
    }else{
        window = [[UIApplication sharedApplication]keyWindow];
    }
    
    return window;
}

@end

使用样例

#import "ViewController.h"
#import "LJKAudioCallAssistiveTouchView.h"


@interface ViewController ()<CAAnimationDelegate, LJKAudioCallAssistiveTouchViewDelegate>
@property (strong, nonatomic) LJKAudioCallAssistiveTouchView *touchView;
@property (strong, nonatomic) UIView *voiceView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (IBAction)showToast:(id)sender {
    
    [self showVoiceView];
    
    if (self.touchView) {
        [self animateTransitionShowVoiceView];
    }
}

- (void)showVoiceView {
    UIWindow *window = [LJKAudioCallAssistiveTouchView getCurrentWindow];
    
    self.voiceView = [[UIView alloc] initWithFrame:window.bounds];
    self.voiceView.backgroundColor = [UIColor blackColor];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [btn setTitle:@"最小化" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(showAssistiveTouchView) forControlEvents:UIControlEventTouchUpInside];
    
    [self.voiceView addSubview:btn];
    btn.center = self.voiceView.center;
    
    UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(btn.frame.origin.x, btn.frame.origin.y + 150, 100, 100)];
    [btn1 setTitle:@"结束对话" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [btn1 addTarget:self action:@selector(closeChat) forControlEvents:UIControlEventTouchUpInside];
    
    [self.voiceView addSubview:btn1];
    
    
    [window addSubview:self.voiceView];
}

- (void)closeChat {
    
    [UIView animateWithDuration:0.4 animations:^{
        self.voiceView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.voiceView removeFromSuperview];
        [self.touchView removeFromSuperview];
        self.voiceView = nil;
        self.touchView = nil;
    }];
    
}

- (void)showAssistiveTouchView {
    
    if (!self.touchView) {
        self.touchView = [[LJKAudioCallAssistiveTouchView alloc] initDefaultTypeWithBegainDate:[[NSDate alloc] init]];
        self.touchView.delegate = self;
        [[LJKAudioCallAssistiveTouchView getCurrentWindow] addSubview:self.touchView]; 
    } else {
        [self.touchView setHidden:NO];
    }
    
    [self animateTransitionShowAssistiveTouchView];
}

- (void)assistiveTouchViewClicked {
    
    [self showVoiceView];
    
    [self animateTransitionShowVoiceView];
}

- (void)animateTransitionShowAssistiveTouchView {

    //浮窗的 frame push时这个是起始 frame ,pop时是结束时的 frame
    self.touchView.alpha = 0;
    CGRect floatBallRect = self.touchView.frame;
    //开始/结束时的曲线
    UIBezierPath *maskFinalBP =  [UIBezierPath bezierPathWithRoundedRect:CGRectMake(floatBallRect.origin.x, floatBallRect.origin.y,floatBallRect.size.width , floatBallRect.size.height) cornerRadius:floatBallRect.size.height/2];
    UIBezierPath *maskStartBP = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0 , self.voiceView.bounds.size.width, self.voiceView.bounds.size.height) cornerRadius:floatBallRect.size.width/2];
    //.layer.mask 是部分显示的原因
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = maskFinalBP.CGPath;
    self.voiceView.layer.mask = maskLayer;
    //动画类
    CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    maskLayerAnimation.fromValue = (__bridge id)(maskStartBP.CGPath);
    maskLayerAnimation.toValue = (__bridge id)((maskFinalBP.CGPath));
    maskLayerAnimation.duration = 0.5;
    maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    maskLayerAnimation.delegate = self;
    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
    //隐藏浮窗
    [UIView animateWithDuration:0.4 animations:^{
        self.voiceView.alpha = 0;
        self.touchView.alpha = 1;
    }];
}

- (void)animateTransitionShowVoiceView {

    self.voiceView.alpha = 0;
    
    //浮窗的 frame push时这个是起始 frame ,pop时是结束时的 frame
    CGRect floatBallRect = self.touchView.frame;
    //开始/结束时的曲线
    UIBezierPath *maskStartBP =  [UIBezierPath bezierPathWithRoundedRect:CGRectMake(floatBallRect.origin.x, floatBallRect.origin.y,floatBallRect.size.width , floatBallRect.size.height) cornerRadius:floatBallRect.size.height/2];
    UIBezierPath *maskFinalBP = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0 , self.voiceView.bounds.size.width, self.voiceView.bounds.size.height) cornerRadius:floatBallRect.size.width/2];
    //.layer.mask 是部分显示的原因
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = maskFinalBP.CGPath;
    self.voiceView.layer.mask = maskLayer;
    //动画类
    CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    maskLayerAnimation.fromValue = (__bridge id)(maskStartBP.CGPath);
    maskLayerAnimation.toValue = (__bridge id)((maskFinalBP.CGPath));
    maskLayerAnimation.duration = 0.5;
    maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    maskLayerAnimation.delegate = self;
    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
    //隐藏浮窗
    [UIView animateWithDuration:0.4 animations:^{
        self.voiceView.alpha = 1;
        self.touchView.alpha = 0;
    }];
}

#pragma mark - CABasicAnimation的Delegate
//动画完成后代理
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{

    if (self.voiceView.alpha == 0) {
        [self.voiceView removeFromSuperview];
    }
    
    if (self.touchView.alpha == 0) {
        [self.touchView setHidden:YES];
    }
}

@end
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容