IOS开发(70)之拖拽手势

1 前言

利用 UIPanGestureRecognizer 这个手势识别器, 来实现图层的拖拽。

2 代码实例

ZYViewController.m

@synthesize helloWorldLabel;
@synthesize panGestureRecognizer;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    /* Let's first create a label */
    CGRect labelFrame = CGRectMake(0.0f, /* X */
                                   0.0f, /* Y */
                                   150.0f, /* 宽 */
                                   100.0f); /* 高 */
    self.helloWorldLabel = [[UILabel alloc] initWithFrame:labelFrame];
    self.helloWorldLabel.text = @"Hello World";
    self.helloWorldLabel.backgroundColor = [UIColor blackColor];
    self.helloWorldLabel.textColor = [UIColor whiteColor];
    self.helloWorldLabel.textAlignment = NSTextAlignmentCenter;
    //确保label可以互动的属性,以便可以激活其方法
    self.helloWorldLabel.userInteractionEnabled = YES;
    [self.view addSubview:self.helloWorldLabel];
    //创建拖拽手势
    self.panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                action:@selector(handlePanGestures:)];
    //无论最大还是最小都只允许一个手指
    self.panGestureRecognizer.minimumNumberOfTouches = 1;
    self.panGestureRecognizer.maximumNumberOfTouches = 1;
    [self.helloWorldLabel addGestureRecognizer:self.panGestureRecognizer];
}

- (void) handlePanGestures:(UIPanGestureRecognizer*)paramSender{
    if (paramSender.state != UIGestureRecognizerStateEnded && paramSender.state != UIGestureRecognizerStateFailed){
        //通过使用 locationInView 这个方法,来获取到手势的坐标
        CGPoint location = [paramSender locationInView:paramSender.view.superview];
        paramSender.view.center = location;
    }
}

运行结果


拖拽后结果


3 结语

以上是所有内容,希望对大家有所帮助。

Demo实例:http://download.csdn.net/detail/u010013695/5366913

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值