How to limit drag and drop for images

My first post, and now I am making an application in Xcode 8.1 using Swift 3

I have 9 images that I made drag-and-drop using touchBegan and affects the functions of movd.

However, they can be moved on the screen at any time, and this can cause them to hide other images that I have. I would like to limit their movement by setting a border for them, so even when the user tries to drag images from this border, they will not be able to.

I created this code in draggedimageview.swift, this allows you to drag and drop images.

I spent a lot of time trying to figure out how to do this, and if someone could help, I would appreciate it.

Thank...

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)
    }
}
+4
2

:

let cx = self.center.x+dx
if (cx > 100) {
   cx = 100
}

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

if, , . , , center.x > 100

+3

" " , :

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

        // This is the area in which the dragging is allowed
        let coolArea = CGRect(x: 0, y: 0, width: 100, height: 100)

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

        // If the allowed area contains the new point, we can assign it
        if coolArea.contains(newCenter) {
            self.center = newCenter
        }
        // else {
        //    print("Out of boundaries!")
        // }

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

, , - , .

+1

Source: https://habr.com/ru/post/1673744/


All Articles