美文网首页
iOS开发中控件的长按截图拖拽

iOS开发中控件的长按截图拖拽

作者: 不疯魔难以成佛 | 来源:发表于2017-01-05 11:24 被阅读0次

    <pre><code>

    import "ViewController.h"

    define UI_WIDTH 80

    define UI_HEIGHT 30

    @interface ViewController ()<UIGestureRecognizerDelegate>

    @property(nonatomic,strong)UILabel *label;

    @property(nonatomic,strong)UIView *snapView;

    @end

    @implementation ViewController

    • (void)viewDidLoad {

      [super viewDidLoad];

      // Do any additional setup after loading the view, typically from a nib.

      [self setUI];

    }

    -(void)setUI{

    self.label = [[UILabel alloc]initWithFrame:CGRectMake(100, 200, UI_WIDTH, UI_HEIGHT)];
    [self.view addSubview:self.label];
    self.label.text = @"长按";
    self.label.textAlignment = NSTextAlignmentCenter;
    self.label.layer.borderWidth = 1;
    self.label.layer.borderColor = [UIColor blackColor].CGColor;
    //用户响应
    self.label.userInteractionEnabled = YES;
    //为label添加一个长按手势
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGest:)];
    longPress.delegate = self;
    [self.label addGestureRecognizer:longPress];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGest:)];
    pan.delegate = self;
    [self.label addGestureRecognizer:pan];
    

    }

    -(void)longPressGest:(UIGestureRecognizer *)gesTure{

    NSLog(@"gesTure = %zd",gesTure.state);
    
    //记录上一次手势的位置
    static CGPoint startPoint;
    //触发长按手势的label
    self.label = (UILabel *)gesTure.view;
    
    if (gesTure.state == UIGestureRecognizerStateBegan) {
        //长按
        
        //获取label截图
        self.snapView = [self.label snapshotViewAfterScreenUpdates:YES];
        self.snapView.center = self.label.center;
        [self.view addSubview:self.snapView];
        
        startPoint = [gesTure locationInView:self.label];
    
        
    }else if(gesTure.state == UIGestureRecognizerStateChanged){
    //移动
        CGFloat tranX = [gesTure locationOfTouch:0 inView:self.view].x - startPoint.x;
        CGFloat tranY = [gesTure locationOfTouch:0 inView:self.view].y - startPoint.y;
        
        //设置截图视图位置
        self.snapView.frame = CGRectMake(tranX, tranY, UI_WIDTH, UI_HEIGHT);
        
        
    }else if (gesTure.state == UIGestureRecognizerStateEnded){
    
        //停止
    }
    

    }

    @end

    相关文章

      网友评论

          本文标题:iOS开发中控件的长按截图拖拽

          本文链接:https://www.haomeiwen.com/subject/bafzvttx.html