iOS 悬浮可拖动可点击按钮

来源:互联网 发布:js 清理cookie 编辑:程序博客网 时间:2024/04/28 17:20

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

做完了记录下:

@implementation SearchResultViewController

{

    UIButton  * moveRedPacket;

}




#pragma mark 红包


//创建移动红包的UI

-(void)CreatMoveRedPacketUI{

    

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

    if (moveRedPacket==nil) {

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

    }

    [moveRedPacketsetBackgroundImage:[UIImageimageNamed:@"red"]forState:UIControlStateNormal];

    [moveRedPacketaddTarget:selfaction:@selector(ClickRedPacket:)forControlEvents:UIControlEventTouchUpInside];

    [moveRedPacketaddGestureRecognizer:panTouch];

    [self.view addSubview:moveRedPacket];

    

}



/**

 *  处理拖动手势

 *

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

 */

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

    //视图前置操作

    [recognizer.view.superviewbringSubviewToFront:recognizer.view];

    

    CGPoint center = recognizer.view.center;

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

    CGPoint translation = [recognizertranslationInView:self.view];

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

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

    [recognizer setTranslation:CGPointZeroinView:self.view];

    

    if (recognizer.state ==UIGestureRecognizerStateEnded) {

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

        CGPoint velocity = [recognizervelocityInView: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滑行到终点

        [UIViewanimateWithDuration:slideFactor*2

                              delay:0

                            options:UIViewAnimationOptionCurveEaseOut

                         animations:^{

                             recognizer.view.center = finalPoint;

                         }

                         completion:nil];

    }

}



0 0
原创粉丝点击