如何在swift中连接两个可拖动的视图

时间:2016-12-08 01:30:04

标签: ios swift

我想创造一种类似益智游戏的游戏。屏幕上有几个可拖动的对象,用户可以将它们连接在一起。当用户将两个对象拖到彼此附近并且当用户释放他们的手指时,我可以使用什么方法,这两个对象将连接在一起。下面是我用来制作两个标签并使它们可拖动的代码(我知道为每个标签制作一个函数非常笨,但现在我只想知道这两个对象的组合是如何工作的)

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)



}

感谢任何帮助过的人。

1 个答案:

答案 0 :(得分:1)

您无法“连接”两个视图 - 它会忽略视图和视图层次结构的工作方式。

  • 但你可以让它“看似连接”。但它会很快变得复杂。在你的简单例子中,一种方法是在拼图板上有三个子视图:两个可见(“str”和“ing”),一个不可见(“string”)。连接后,隐藏“str”和“ing”并显示“string”子视图。也许展示一些引人注目的动画,看起来真的像是在连接。

  • 另一个想法(取决于拼图的类型)是让它成为旧“浓缩”游戏的变体。在那里,最后的拼图板隐藏在各种编号的正方形后面。在你的游戏中,你可能会让“棋子”有一个特定的位置,他们需要移动到(成对?),当用户这样做时 - 再次 - 使它看起来连接,也许是一些动画。 / p>

如果我不在这里 - 并且有人真正有办法将两个UIViews连接成一个 - 我很乐意删除我的答案(以及回答投票)。