在手指下拖动UIView [英] Dragging UIView under finger

查看:137
本文介绍了在手指下拖动UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想点击UIView并拖动并按照我的手指操作,简单就够了。但最简单的方法是将对象中心设置为点击发生的位置(这不是我想要的),我希望它移动,就好像你在任何地方抓住它一样抓住了对象。

I want to tap on a UIView and drag and have that view follow my finger, simple enough. But the easiest way of doing this is by setting the objects center to where the tap happened (Which is not what I want), I want it to move as if you grabbed the object wherever you tapped it.

这是一种非常有用的方法,它是在其中一个iTunes U视频中引用的。该脚本没有使用deltaX,deltaY来拖动你点击它下面的图像,而不是让它位于你的手指下方,但我不记得那个代码是什么!

There was a very useful way of doing this and it was reference in one of the iTunes U videos. The script didn't use deltaX, deltaY for dragging the image underneath where you tapped on it instead of having it center underneath your finger but I can't remember what that code was!

有没有人引用此代码?或者也许有一种有效的方法在没有uiview.center = tap.center概念的情况下在手指下移动UIViews?

Does anyone have a reference to this code? Or perhaps have an efficient way of moving UIViews under a finger without having the uiview.center = tap.center concept?

推荐答案

以下代码是一个简单的手势识别器的示例,它将允许面板/视图移动。您不是修改中心,而是修改原点[基本上通过为目标视图设置新框架]。

The following code is an example of a simple gesture recognizer that will allow panel / view movement. Instead of modifying the center, you're modifying the origin point [basically by setting a new frame for the target view].

您可以在您的情况下对此进行优化,以便您'不需要深入了解gesture.view ...等

You can optimize this in your situation so you're not having to drill down into the gesture.view... etc

-(void)dragging:(UIPanGestureRecognizer *)gesture
{
    if(gesture.state == UIGestureRecognizerStateBegan)
    {
        //NSLog(@"Received a pan gesture");
        self.panCoord = [gesture locationInView:gesture.view];


    }
    CGPoint newCoord = [gesture locationInView:gesture.view];
    float dX = newCoord.x-panCoord.x;
    float dY = newCoord.y-panCoord.y;

gesture.view.frame = CGRectMake(gesture.view.frame.origin.x+dX, gesture.view.frame.origin.y+dY, gesture.view.frame.size.width, gesture.view.frame.size.height);
 }

Swift 4:

@objc func handleTap(_ sender: UIPanGestureRecognizer) {
        if(sender.state == .began) {
            self.panCoord = sender.location(in: sender.view)
        }

        let newCoord: CGPoint = sender.location(in: sender.view)

        let dX = newCoord.x - panCoord.x
        let dY = newCoord.y - panCoord.y

        sender.view?.frame = CGRect(x: (sender.view?.frame.origin.x)!+dX, y: (sender.view?.frame.origin.y)!+dY, width: (sender.view?.frame.size.width)!, height: (sender.view?.frame.size.height)!)
    }

这篇关于在手指下拖动UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆