Search code examples
iosswiftdraggable

How do I limit the dragging area for image views


My first post and I am currently making an app in Xcode 8.1 using Swift 3

I have 9 images that I have made draggable with touchesBegan and touchesMoved functions.

However they are able to be dragged ANYWHERE on the screen and this can cause them to cover up other images I have. I would like to limit their movement by setting a boundary for them so that even when the user tries to drag the images out of that boundary they wont be able to.

I have created this code in draggedimageview.swift this allows the Image views to be dragged.

I have been spending a long time trying to figure out how to do this and if anyone can help I would appreciate it.

Thanks...

import UIKit

class DraggedImageView: UIImageView {

    var startLocation: CGPoint?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startLocation = touches.first?.location(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        let currentLocation = touches.first?.location(in: self)
        let dx = currentLocation!.x - startLocation!.x
        let dy = currentLocation!.y - startLocation!.y

        self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
    }
}

Solution

  • You can do this:

    let cx = self.center.x+dx
    if (cx > 100) {
       cx = 100
    }
    
    self.center = CGPoint(x: cx, y: self.center.y+dy)
    

    But alter the if based on what you are trying to do. This clamps it so that it cannot be moved to a position where center.x > 100