前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS 悬浮可拖动可点击按钮

iOS 悬浮可拖动可点击按钮

作者头像
星宇大前端
发布2019-01-15 11:16:50
2.5K0
发布2019-01-15 11:16:50
举报
文章被收录于专栏:大宇笔记大宇笔记

项目里下完单之后要悬浮红包,类似饿了吗那种。

做完了记录下:

@implementation SearchResultViewController

{

UIButton  * moveRedPacket;

}

#pragma mark 红包

//创建移动红包的UI

-(void)CreatMoveRedPacketUI{

UIPanGestureRecognizer   *  panTouch    =   [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];

if (moveRedPacket==nil) {

moveRedPacket =   [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-120, ScreenHeight-120, 80, 85)];

    }

    [moveRedPacket setBackgroundImage:[UIImage imageNamed:@"red"] forState:UIControlStateNormal];

    [moveRedPacket addTarget:self action:@selector(ClickRedPacket:) forControlEvents:UIControlEventTouchUpInside];

    [moveRedPacket addGestureRecognizer:panTouch];

    [self.view addSubview:moveRedPacket];

}

/**

 *  处理拖动手势

 *

 *  @param recognizer 拖动手势识别器对象实例

 */

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {

//视图前置操作

    [recognizer.view.superview bringSubviewToFront:recognizer.view];

CGPoint center = recognizer.view.center;

CGFloat cornerRadius = recognizer.view.frame.size.width / 2;

CGPoint translation = [recognizer translationInView:self.view];

//NSLog(@"%@", NSStringFromCGPoint(translation));

    recognizer.view.center = CGPointMake(center.x + translation.x, center.y + translation.y);

    [recognizer setTranslation:CGPointZero inView:self.view];

if (recognizer.state == UIGestureRecognizerStateEnded) {

//计算速度向量的长度,当他小于200时,滑行会很短

CGPoint velocity = [recognizer velocityInView:self.view];

CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));

CGFloat slideMult = magnitude / 200;

//NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult); //e.g. 397.973175, slideMult: 1.989866

//基于速度和速度因素计算一个终点

float slideFactor = 0.1 * slideMult;

CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),

                                         center.y + (velocity.y * slideFactor));

//限制最小[cornerRadius]和最大边界值[self.view.bounds.size.width - cornerRadius],以免拖动出屏幕界限

        finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius),

self.view.bounds.size.width - cornerRadius);

        finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius),

self.view.bounds.size.height - cornerRadius);

//使用 UIView 动画使 view 滑行到终点

        [UIView animateWithDuration:slideFactor*2

delay:0

options:UIViewAnimationOptionCurveEaseOut

animations:^{

                             recognizer.view.center = finalPoint;

                         }

completion:nil];

    }

}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年11月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档