如何限制图像视图的拖动区域



我的第一篇文章,我目前正在使用 Swift 3 在 Xcode 8.1 中制作一个应用程序

我有 9 张图像,我已经用触摸开始和触摸移动功能进行了拖动。

但是,它们可以在屏幕上的任何位置拖动,这可能会导致它们掩盖我拥有的其他图像。我想通过为它们设置边界来限制它们的移动,这样即使用户试图将图像拖出该边界,他们也无法这样做。

我已经在拖动图像视图中创建了此代码.swift这允许拖动图像视图。

我一直在花很长时间试图弄清楚如何做到这一点,如果有人可以提供帮助,我将不胜感激。

谢谢。。。

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)
    }
}

你可以这样做:

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

尝试在矩形中定义"允许的区域",例如:

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)
    }
}

如果您希望在用户拖出边界时发生不同的事情,则可能需要更改代码。

从包含 UIImageView 的视图中获取"允许的区域">

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
        let coolArea = (self.superview?.bounds)!
        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
            print("touchesMoved")
        }
         else {
            print("Out of boundaries!")
         }
    }
}

最新更新