iOS开发知识小集日常小知识点

封装一个拖动悬停的按钮

2018-08-03  本文已影响421人  moonCoder

需求就是在首页有一个按钮,你可以拖动在屏幕上滑动,最终位置是自己靠边悬靠。
上代码:

//
//  KZWSuspensionButton.m
//  kongzhongfinancial
//
//  Created by ouyang on 2018/8/2.
//  Copyright © 2018年 ouy. All rights reserved.
//

#import "KZWSuspensionButton.h"

@implementation KZWSuspensionButton

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];//创建手势
        [self setUserInteractionEnabled:YES];
        [self addGestureRecognizer:pan];
    }
    return self;
}

- (void)handlePan: (UIPanGestureRecognizer *)rec{
    
    CGPoint point = [rec translationInView:[UIApplication sharedApplication].keyWindow];
    
    NSLog(@"%f,%f",point.x,point.y);
    
    rec.view.center = CGPointMake(rec.view.center.x + point.x, rec.view.center.y + point.y);
    
    [rec setTranslation:CGPointZero inView:[UIApplication sharedApplication].keyWindow];
    
    if (rec.state == UIGestureRecognizerStateEnded) {
        if (self.frame.origin.x < SCREEN_WIDTH/2) {
            [self viewMove:rec.view point:CGPointMake(20 , rec.view.center.y + point.y)];
            if (self.frame.origin.y < KZW_StatusBarAndNavigationBarHeight ) {
                [self viewMove:rec.view point:CGPointMake(20 , KZW_StatusBarAndNavigationBarHeight + 20)];
            }
            if (self.frame.origin.y > SCREEN_HEIGHT - KZW_TabbarHeight) {
                [self viewMove:rec.view point:CGPointMake(20 , SCREEN_HEIGHT - KZW_TabbarHeight - 20)];
            }
        }else {
            [self viewMove:rec.view point:CGPointMake(SCREEN_WIDTH - 20 , rec.view.center.y + point.y)];
            if (self.frame.origin.y < KZW_StatusBarAndNavigationBarHeight ) {
                [self viewMove:rec.view point:CGPointMake(SCREEN_WIDTH - 20 , KZW_StatusBarAndNavigationBarHeight + 20)];
            }
            if (self.frame.origin.y > SCREEN_HEIGHT - KZW_TabbarHeight) {
                [self viewMove:rec.view point:CGPointMake(SCREEN_WIDTH - 20 , SCREEN_HEIGHT - KZW_TabbarHeight - 20)];
            }
        }
    }
}

- (void)viewMove:(UIView *)view point:(CGPoint)point {
    [UIView animateWithDuration:0.6
                                   delay:0
                                  options:UIViewAnimationOptionCurveEaseOut
                               animations:^{
                                       view.center = point;
                                   }
                               completion:nil];
}

@end

一个初始化方法,一个手势添加,位置我是直接基于window写的,最后加了一个靠边的移动动画。然后就OK,这样就算封装完了,你有需要的事件处理也可以直接在这写。

上一篇下一篇

猜你喜欢

热点阅读