#import "ViewController.h"
#define BtnW 80
#define NavH 64
#define TabH 48
@interface ViewController ()
// 悬浮按钮
@property(nonatomic,strong) UIButton * moveButton;
@property(nonatomic)CGRect rect;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self CreatMoveRedPacketUI];
}
- (void)CreatMoveRedPacketUI
{
_rect = CGRectMake([UIScreen mainScreen].bounds.size.width - BtnW,[UIScreen mainScreen].bounds.size.height - TabH - BtnW,BtnW,BtnW);
[self.view addSubview:self.moveButton];
}
#pragma mark悬浮按钮点击事件
- (void)ClickRedPacket:(UIButton *)sender
{
NSLog(@"点击");
}
#pragma mark处理拖动手势
- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
// button置顶
[recognizer.view.superview bringSubviewToFront:recognizer.view];
// button 中心点
CGPoint center = recognizer.view.center;
// 移动方向距离
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(center.x + translation.x, center.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self.view];
if (recognizer.state == UIGestureRecognizerStateBegan)
{
_moveButton.alpha = 0.5;
}
if (recognizer.state == UIGestureRecognizerStateChanged)
{
_moveButton.alpha = 0.5;
}
CGPoint centerNew = recognizer.view.center;
if (recognizer.state == UIGestureRecognizerStateEnded)
{
_moveButton.alpha = 1;
if (center.x < BtnW/2)
{
centerNew.x = BtnW/2;
}
if (center.x > self.view.frame.size.width - BtnW/2)
{
centerNew.x = self.view.frame.size.width - BtnW/2;
}
if (center.y < NavH + BtnW/2)
{
centerNew.y = NavH + BtnW/2;
}
if (center.y > self.view.frame.size.height - TabH - BtnW/2)
{
centerNew.y = self.view.frame.size.height - TabH - BtnW/2;
}
recognizer.view.center = centerNew;
}
}
#pragma mark 长按事件
- (void)longPress:(UILongPressGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateBegan)
{
NSLog(@"开始长按");
_moveButton.frame =_rect;
}
else
{
NSLog(@"长按手松开");
}
}
#pragma mark 创建悬浮按钮
-(UIButton *)moveButton{
if (!_moveButton)
{
UIButton *moveButton =[[UIButton alloc]initWithFrame:_rect];
NSString *imagName = @"001";
[moveButton setBackgroundImage:[UIImage imageNamed:imagName] forState:UIControlStateNormal];
[moveButton setBackgroundImage:[UIImage imageNamed:imagName] forState:UIControlStateHighlighted];
[moveButton addTarget:self action:@selector(ClickRedPacket:)forControlEvents:UIControlEventTouchUpInside];
//点击移动
UIPanGestureRecognizer *panTouch = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
[moveButton addGestureRecognizer:panTouch];
// 长按隐藏
UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
longPressGR.minimumPressDuration =0.8;
[moveButton addGestureRecognizer:longPressGR];
_moveButton = moveButton;
}
return _moveButton;
}
@end