[手势与触摸]用拖动手势识别器实现可供拖拽的视图

本文介绍如何在iOS中通过实现手势识别器,创建一个可以被用户拖动的视图。通过在视图中添加一个UIPanGestureRecognizer,并在用户触摸和拖动时更新视图的位置,实现拖动手势的响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  DragView.m
//  iOS核心开发手册

#import "DragView.h"

/*
拖动手势识别器可以侦测拖拽手势,只要系统检测到拖动手势,就会触发你所指定的回调方法
 */

@implementation DragView
{
    //用来保存视图原来的位置
    CGPoint previousLocation;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //由于这个是ImaveView,所以要开启交互功能
        self.userInteractionEnabled = YES;
        
        //在初始化时,向视图添加识别器
        //当用户在DragView实例上面执行拖拽时,就会触发 handlePan: 回调方法。
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handelPan:)];
        self.gestureRecognizers = @[panRecognizer];
    }
    return self;
}

//回调方法
- (void)handelPan:(UIPanGestureRecognizer *)panRecognizer
{
    //更新DragView的中心点,使之于用户所拖拽的距离相符
    CGPoint translation = [panRecognizer translationInView:self.superview];
    
    //移动视图的中心点
    self.center = CGPointMake(previousLocation.x + translation.x, previousLocation.y + translation.y);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //用户所触摸的DragView会显示在屏幕最前面
    [self.superview bringSubviewToFront:self];
    
    //记录位置
    previousLocation = self.center;
}


@end
本篇只有基础代码,更多代码查看上一篇:《 [手势与触摸]创建可以拖动的视图
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值