简体   繁体   中英

How do I drag a UIImage in swift 4

I currently have the code to move the UIImage to wherever I tap on the screen, however my app requires the user to be able to drag the image about on the screen and my current code doesn't do that. I am new to the language so any help would be appreciated. Here is my current code for getting the location of the touch:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?{ if let touch = touches.first { let location = touch.location(in: self.view)

You could do it yourself by implementing both touchesBegan() and touchesMoved() , but you'd be better off using a UIPanGestureRecognzier . I'd suggest finding a sample project that lets you drag views using UIPanGestureRecognzier . It will save you some head-scratching.

I had made cube which is basically a UIView that can be dragged around and the info changes inside the cube. I used the following function to drag the cube in the view. See if it helps

   var draggableCube = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))

@objc func panGestureDetected(panGestureRecognizer: UIPanGestureRecognizer) {
        
    let translation = panGestureRecognizer.translation(in: self.view)
    var changeX : CGFloat = 0
    var changeY : CGFloat = 0
    
    if translation.x + self.draggableCube.frame.maxX > self.view.bounds.maxX {
        // prevents it to go outside of the bounds from right side
        changeX = self.view.bounds.maxX - self.draggableCube.frame.maxX
    } else if translation.x + self.draggableCube.frame.minX < self.view.bounds.minX{
        // prevents it to go outside of the bounds from right side
        changeX = self.view.bounds.minX - self.draggableCube.frame.minX
    } else {
        // translation is within limits
        changeX = translation.x
    }
    if translation.y + self.draggableCube.frame.maxY > self.view.bounds.maxY {
        // prevents it to go outside of the bounds from bottom
        changeY = self.view.bounds.maxY - self.draggableCube.frame.maxY
    } else if translation.y + self.draggableCube.frame.minY < self.view.bounds.minY {
        // prevents it to go outside of the bounds from top
        changeY = self.view.bounds.minY - self.draggableCube.frame.minY
    } else {
        // translation is within limits
        changeY = translation.y
    }

    self.draggableCube.center = CGPoint(x: self.draggableCube.center.x + changeX, y: self.draggableCube.center.y + changeY)

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

    if panGestureRecognizer.state == .ended {
        // implement action what you want to do after the gragging ended
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM