修改约束 [英] Modifying Constraints

查看:104
本文介绍了修改约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为练习学习斯威夫特和iOS开发我决定把突围游戏。就在一开始我遇到了一个简单的问题,我无法找到一个简单的解决方案。

As an exercise for learning Swift and iOS development I decided to make the Breakout game. Right at the start I encountered a simple problem, that I can't find a simple solution for.

我开始用桨。我创建了一个 gameView 这将是本场比赛的容器。我还创建了 paddleView 并补充说,将会把桨在合适的位置约束。下面是我有:

I started with the paddle. I created a gameView which will be the container for the game. I also created the paddleView and added constraints that will put the paddle in the right position. Here's what I have:

我还添加了锅手势识别的定位桨的 center.x 位置。

I also added a pan gesture recognizer that positions the paddle's center.x position.

下面的问题:当我改变方向,桨移动到前更改中心的位置无关

Here's the problem: when I change orientation, the paddle moves to center regardless of the position prior to the change.


我试图创建中心X对齐约束 viewWillTransitionToSize 删除它,并恢复$ P的出口在$ pvious位置 viewDidLayoutSubviews 但桨的 origin.x 总是0,我也尝试过修改的约束,也许改变乘数,但仍然未果。

I tried creating an outlet of the Center X Alignment Constraint, removing it in viewWillTransitionToSize, and restoring previous position in viewDidLayoutSubviews but paddle's origin.x was always 0. I also tried modifying the constraint, maybe changing the multiplier, but still unsuccessful.

我知道有一个简单的解决方案,但我不能找到它。

I know there's a simple solution to this, but I can't find it.

有人能帮忙吗?

推荐答案

您不应该修改视图center.x在平移手势的处理程序,因为你的约束会休息。相反,你应该建立约束插座(让说了约束:view.center.x等于superview.center.x),并在你的盘支架改变它的恒定值。

You should not modify view center.x in your pan gesture handler because your constrains will be break. Instead you should create constraint outlet (let say for constraint : view.center.x equal superview.center.x) and change its constant value in your pan handler.

@IBOutlet weak var centerAlignment: NSLayoutConstraint!

@IBAction func handleDrag(sender: UIPanGestureRecognizer) {

    let xPosition = sender.locationInView(self.view).x

    if  xPosition >= 0 && xPosition <= self.view.frame.size.width{

        centerAlignment.constant = xPosition - self.view.frame.size.width / 2

    } else if xPosition > self.view.frame.size.width {

        centerAlignment.constant = self.view.frame.size.width / 2

    } else {

        centerAlignment.constant = -self.view.frame.size.width / 2
    }

}

这篇关于修改约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆