Changing restrictions

As an exercise for learning Swift and iOS, I decided to do Breakout . Right from the start, I ran into a simple problem that I cannot find an easy solution for.

I started with the paddle. I have created gameView

which will be the container for the game. I've also created paddleView

and added restraints that put the paddle in the correct position. Here's what I have:

enter image description here

I also added a gesture recognizer that positions the position of the paddle center.x

.

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

enter image description hereenter image description here

I tried to create an exit from Center X Alignment Constraint

by deleting it in viewWillTransitionToSize

and restoring the previous position to viewDidLayoutSubviews

, but the paddle was origin.x

always 0. I also tried changing the constraint, possibly changing multiplier

, but still unsuccessful.

I know this is a simple solution, but I cannot find it.

Does anyone help?

+3


source to share


1 answer


You shouldn't change view center.x in your gesture handler because your constraints will break. Instead, you should create a constraint exit (let's say for constraint: view.center.x equals 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
    }

}

      

0


source