#import <UIKit/UIKit.h>
@interface QHFloatButton : UIButton
- (void)showInView:(UIView *)view;
@end
#import "QHFloatButton.h"
@interface QHFloatButton ()
@property (nonatomic, strong) UIView *baseView;
@end
@implementation QHFloatButton
- (instancetype)initWithFrame:(CGRect)frame{
if(self = [super initWithFrame:frame]){
[self setup];
}
return self;
}
- (void)setup{
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
[self addGestureRecognizer:panGesture];
}
- (void)showInView:(UIView *)view{
self.baseView = view;
//初始化懸浮按鈕的frame和位置
self.frame = CGRectMake(0, 0, 60.0, 60.0);
self.center = CGPointMake(view.bounds.size.width, view.center.y);
[view addSubview:self];
}
- (void)panAction:(UIPanGestureRecognizer *)pan{
switch (pan.state) {
case UIGestureRecognizerStateBegan:{
self.alpha = 1;
}
break;
case UIGestureRecognizerStateChanged:{
CGPoint point = [pan locationInView:self.baseView];
self.center = point;
}
break;
case UIGestureRecognizerStateEnded:{
CGPoint point = [self getResultPoint];
[UIView animateWithDuration:0.3 animations:^{
self.alpha = 0.5;
self.center = point;
} completion:^(BOOL finished) {
}];
}
break;
default:{
self.center = CGPointMake(self.baseView.bounds.size.width, self.baseView.center.y);
}
break;
}
}
- (CGPoint)getResultPoint{
CGRect baseFrame = self.baseView.frame;
CGPoint resultPoint = CGPointZero;
if(self.center.x > baseFrame.size.width / 2.0){
// if(self.center.y > baseFrame.size.height / 2.0){
//貼右邊
resultPoint = CGPointMake(baseFrame.size.width, self.center.y);
// }else{
// //貼頂部
// resultPoint = CGPointMake(self.center.x, 0);
// }
}else{
// if(self.center.y > baseFrame.size.height / 2.0){
//貼左邊
resultPoint = CGPointMake(0, self.center.y);
// }else{
// //貼頂部
// resultPoint = CGPointMake(self.center.x, 0);
// }
}
return resultPoint;
}
@end
使用方法如下:
#pragma mark 懸浮按鈕
- (void)showCaptionBtn{
_floatBtn = [[QHFloatButton alloc]init];
[_floatBtn setImage:IMAGENAMED(@"home_icon_captain") forState:UIControlStateNormal];
[_floatBtn addTarget:self action:@selector(captainAction) forControlEvents:UIControlEventTouchUpInside];
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
[_floatBtn showInView:app.window];
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[_floatBtn setHidden:NO];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[_floatBtn setHidden:YES];
}
效果圖

版權聲明:本文為CSDN部落客「weixin_34416754」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。
原文連結:https://blog.csdn.net/weixin_34416754/article/details/92316578