iOS自定义悬浮按钮,Objective-C可拖动的浮动按钮,iOS浮动图标,类似AssistiveTouch的浮动漂浮按钮

作者: 小新

发布于 2021-10-18 | 最后更新 2021-10-18


最近弄个小项目,又用到这效果,翻了下以前的代码来用,觉得有点意思,顺便放出来供大家参考,

好像是2015年的时候,某些大公司,如“京东”在APP的首页上弄了个漂浮的图标,当时我在的公司也立马跟着弄一个,

类似这样的模仿行为我已经习惯了!就是在界面上弄一个漂浮的按钮,能移动和点击响应,也不是随便漂和移,要吸附在左右两边。

先上代码

#import <UIKit/UIKit.h>
 
@interface KADDragImageView : UIImageView
 
-(void)setAction:(NSString*)action;
 
-(void)setActionBlock:(void(^)())block;
 
@end

#import "KADDragImageView.h"
 
@interface KADDragImageView()<KADUmengHomeProtocol>
{
    CGPoint startLocation;
    NSString *_action;
    void(^_actionBlock)();
}
@end
@implementation KADDragImageView
 
-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapMe)];
        [self addGestureRecognizer:tap];
    }
    return self;
}
 
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:self];
    startLocation = pt;
    [[self superview] bringSubviewToFront:self];
}
 
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:self];
    float dx = pt.x - startLocation.x;
    float dy = pt.y - startLocation.y;
    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    //
    float halfx = CGRectGetMidX(self.bounds);
    newcenter.x = MAX(halfx, newcenter.x);
    newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x);
    //
    float halfy = CGRectGetMidY(self.bounds);
    newcenter.y = MAX(halfy, newcenter.y);
    newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y);
    //
    self.center = newcenter;
}
 
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint point = self.center;
    if (point.x>[self superview].width/2.0) {
        [UIView animateWithDuration:0.2 animations:^{
            self.x = [self superview].width-self.width;
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.x = 0;
        }];
    }
}
 
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}
 
-(void)tapMe {
    debugLog(@"touch float icon ....");
    if (![NSString IsNullOrWhiteSpace:_action]) {
        //注:这里我删掉两行跟业务有关的代码
    }
    if(_actionBlock){ _actionBlock(); }
}
 
-(void)setAction:(NSString *)action {
    _action = action;
}
 
-(void)setActionBlock:(void (^)())block {
    _actionBlock = block;
}
 
@end

简单说下写法:

1、自定义一个类继承于UIImageView,这样就可以显示图标;

2、然后在initWithFrame:方法给它添加点击手势,这样就能响应点击了;

3、点击后做什么事情?这个可由外部实现,请看上面的 setActionBlock: 方法;

4、怎样被手指拖动?请看 touchesBegan:withEvent: 和 touchesModed:withEvent: 方法,就是计算移了多少然后改变自己的center;

5、停止时吸附到左右两边,请看 touchesEnded:withEvent: 方法,计算自己当前的位置决定回到左边或者右边。

使用的时候,直接创建KADDragImageView类的实例,添加到要显示的视图中如self.view即可!