Draggable UIView Swift 3

2019-03-08 11:29发布

问题:

I want to be able to drag the objects on the screen, but they wont. I tried everything but still cant.

Here are the code.

func panGesture(gesture: UIPanGestureRecognizer) {
    switch gesture.state {
    case .began:
        print("Began.")
        for i in 0..<forms.count {
            if forms[i].frame.contains(gesture.location(in: view)) {
                gravity.removeItem(forms[i])
            }
        }
    case .changed:
        let translation = gesture.translation(in: forms[1])

        gesture.view!.center = CGPoint(x: gesture.view!.center.x + translation.x, y: gesture.view!.center.y + translation.y)

        gesture.setTranslation(CGPoint.zero, in: self.view)

        print("\(gesture.view!.center.x)=\(gesture.view!.center.y)")
        print("t;: \(translation)")
    case .ended:
        for i in 0..<forms.count {
            if forms[i].frame.contains(gesture.location(in: view)) {
                gravity.addItem(forms[i])
            }
        }
        print("Ended.")
    case .cancelled:
        print("Cancelled")
    default:
        print("Default")
    }
}

Also they have gravity. The forms are squares and circles.

Explanation: in .began - i disable the gravity for selected form. in .changed - i try to change the coordinates. in .end - i enable again gravity.

ScreenShot.

回答1:

Step 1 : Take one View which you want to drag in storyBoard.

@IBOutlet weak var viewDrag: UIView!

Step 2 : Add PanGesture.

var panGesture       = UIPanGestureRecognizer()

Step 3 : In ViewDidLoad adding the below code.

override func viewDidLoad() {
    super.viewDidLoad()

    panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.draggedView(_:)))
    viewDrag.isUserInteractionEnabled = true
    viewDrag.addGestureRecognizer(panGesture)

}

Step 4 : Code for draggedView.

func draggedView(_ sender:UIPanGestureRecognizer){
    self.view.bringSubview(toFront: viewDrag)
    let translation = sender.translation(in: self.view)
    viewDrag.center = CGPoint(x: viewDrag.center.x + translation.x, y: viewDrag.center.y + translation.y)
    sender.setTranslation(CGPoint.zero, in: self.view)
}

Step 5 : Output.



回答2:

Use below code for Swift 2.3

@IBOutlet weak var viewDrag: UIView!
var panGesture = UIPanGestureRecognizer()

In ViewDidLoad adding the below code.

override func viewDidLoad() {
super.viewDidLoad()
 var panGesture = UIPanGestureRecognizer(target: self, action:("draggedView:"))
 viewDrag.userInteractionEnabled = true
 viewDrag.addGestureRecognizer(panGesture)
}

func draggedView(sender:UIPanGestureRecognizer){
    self.view.bringSubviewToFront(viewDrag)
    let translation = sender.translationInView(self.view)
    viewDrag.center = CGPoint(x: viewDrag.center.x + translation.x, y: viewDrag.center.y + translation.y)
    sender.setTranslation(CGPoint.zeroPoint, inView: self.view)
}

Hope this will help someone.