iOS 悬浮可拖动可点击按钮

2022-12-22 17:08:10 浏览数 (1)

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

做完了记录下:

@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];

    }

}

ios

0 人点赞