Search code examples
iosswiftimageviewcgrect

Why do my UIImageView coordinates change when I update label value?


I want to move my UIImageView when a certain button is clicked. I have this code:

@IBOutlet weak var counter: UILabel!
@IBOutlet weak var indexCrow: UIImageView!

var crow = 0

@IBAction func plusButton(sender: UIButton) {  // Plus Button
    indexCrow.frame = CGRect(x: indexCrow.frame.origin.x + 20, y: indexCrow.frame.origin.y, width: indexCrow.frame.size.width, height: indexCrow.frame.size.height)
    crow++
    counter.text = String(crow)

}

If I remove the line counter.text = String(crow), my image view moves correctly, but my label does not update. If I write counter.text = String(crow) my label updates, but my image view does not move.

What I do wrong?


Solution

  • AutoLayout is running when you update the label and placing your image back to where it started. You have several options to deal with this. Choose one:

    1. Turn off AutoLayout. Most don't choose this option because they want their layouts to work on multiple devices.

    2. Create your imageView programmatically instead of in Interface Builder. If you do this, it won't be subject to AutoLayout and you can move it freely.

    3. Place your imageView using AutoLayout constraints. Add IBOutlets to those constraints and update the constant values in code instead of modifying the frame.

    4. When plusButton is called, store the new frame for your imageView in a property in your ViewController, and then put that frame in place in an override of viewDidLayoutSubviews which happens after AutoLayout runs.