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

来源:互联网 发布:网络实时监控软件 编辑:程序博客网 时间:2024/06/05 04:16
////  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
本篇只有基础代码,更多代码查看上一篇:《[手势与触摸]创建可以拖动的视图》
0 0
原创粉丝点击