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?
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:
Turn off AutoLayout. Most don't choose this option because they want their layouts to work on multiple devices.
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.
Place your imageView using AutoLayout constraints. Add IBOutlet
s to those constraints and update the constant
values in code instead of modifying the frame.
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.