防止拖动的对象离开其指定的视图

时间:2014-10-31 22:21:36

标签: ios swift

我试图在iOS中使用swift编写一段代码,创建一个用户触摸的方块并让它们拖动它。问题是,我希望它可以移动的区域被限制在创建它的UIView中。

以下代码几乎有效。您只能通过在框内按下来创建方块,但是您可以将其拖动到所需的位置。如果盒子留在围栏中,我不会挑剔#34;你用手指跟踪或者只是消失,直到你把手指放回去,但我无法在屏幕上显示它。

我对此很陌生,所以如果有更好的方法,我很高兴能够得到纠正。

class ViewController: UIViewController {

var dragableSquare = UIView()   // a square that will appear on press and be dragged around
var fence = UIView()            // a view that the square should be confined within

override func viewDidLoad() {
    super.viewDidLoad()

    // define the fence UIView and it to view
    fence.frame = CGRectMake(view.frame.width/2 - 100, view.frame.height/2 - 100, 200, 200)
    fence.backgroundColor = UIColor.grayColor()
    view.addSubview(fence)

    // give the fence a gesture recognizer
    var pressRecog = UILongPressGestureRecognizer(target: self, action: "longPress:")
    pressRecog.minimumPressDuration = 0.001
    fence.addGestureRecognizer(pressRecog)
}


func longPress(gesture: UILongPressGestureRecognizer) {
    print("press!")

    // get location of the press
    var touchPoint = gesture.locationInView(fence)

    // When the touch begins place the square at that point
    if gesture.state == UIGestureRecognizerState.Began {
        print("began")

        // create and add square to fence view
        dragableSquare.frame = CGRectMake(touchPoint.x-5, touchPoint.y-5, 10, 10)
        dragableSquare.backgroundColor = UIColor.blueColor()
        self.fence.addSubview(dragableSquare)


    // While the press continues, update the square's location to the current touch point
    } else {
        print("moving")
        dragableSquare.center = touchPoint
    }
}

我刚加入了堆栈溢出,我对社区的慷慨和乐于助人的印象非常深刻。我希望我能获得足够的经验,尽快开始帮助他人。

1 个答案:

答案 0 :(得分:1)

您可以使用CGRectIntersection获取视图之间的交叉矩形的大小。在您的情况下,只要正方形和围栏之间的交叉矩形与正方形相同(意味着正方形仍然完全在围栏内),您希望继续移动正方形。所以你的else子句应该是这样的,

} else {
    print("moving")
        if CGRectIntersection(dragableSquare.frame, fence.bounds).size == dragableSquare.frame.size {
            dragableSquare.center = touchPoint
        }
}