Swift如何把屏幕上能够拖动的两个物件连接到一起?

问与答 · ZachL3 · 发布于 5 个月前 · 470 次阅读

我想做一个类似于拼图的游戏,屏幕上有几个拼图块。请问如何在用户把其中一个拼图块拖到另一个旁边松手之后两个拼图快能够连到一起。以下的代码是我用来创造了两个label,让后让这两个label能够被移动。

override func viewDidLoad() {
        super.viewDidLoad()


        let label = UILabel(frame: CGRectMake(UIScreen.mainScreen().bounds.width / 2 - 100, UIScreen.mainScreen().bounds.height / 2 - 100, 100, 50))
        let label2 = UILabel(frame: CGRectMake(UIScreen.mainScreen().bounds.width / 2 - 100, UIScreen.mainScreen().bounds.height / 2 - 200, 100, 50))

        label.text = "Str"
        label.textAlignment = NSTextAlignment.Center
        label.backgroundColor = UIColor.greenColor()
        self.view.addSubview(label)

        label2.text = "ing"
        label2.textAlignment = NSTextAlignment.Center
        label2.backgroundColor = UIColor.greenColor()
        self.view.addSubview(label2)



         let gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
        label.addGestureRecognizer(gesture)
        label.userInteractionEnabled = true

        let gesture2 = UIPanGestureRecognizer(target: self, action: Selector("wasDragged1:"))
        label2.addGestureRecognizer(gesture2)
        label2.userInteractionEnabled = true



    }

    func wasDragged(gesture: UIPanGestureRecognizer) {
         let translation = gesture.translationInView(self.view)
        if let label = gesture.view {

        label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y)

        }
        gesture.setTranslation(CGPointZero, inView: self.view)


    }

    func wasDragged1(gesture:UIPanGestureRecognizer) {

        let translation = gesture.translationInView(self.view)
        if let label = gesture.view {

            label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y)

        }
        gesture.setTranslation(CGPointZero, inView: self.view)



    }
共收到 0 条回复
回帖