Benjamin Reenk Benjamin Reenk - 5 months ago 70
Swift Question

iOS Swift - moving image with slider

I have some problems moving an UIImageView using a slider. This is my code I'm currently using:

@IBOutlet weak var titanic: UIImageView!

...

let screenWidth = UIScreen.mainScreen().bounds.width
let titanicWidth = titanic.bounds.size.width
let viewcenter = titanicWidth / 2
let slidervalue = CGFloat(sender.value)
let value = (screenWidth * slidervalue * (1.0 - titanicWidth / screenWidth)) + viewcenter
titanic.center.x = CGFloat(value)
print(value)


Actually, I can move the image with this code, BUT: somehow the image always "jumps" back to it's origin position in the middle of the screen, without moving the slider at all... Do you have any idea, how this can happen? I already checked the inspector on the right for some strange attributes which may cause this effect, but no luck...

Answer

Unless you unchecked the "use AutoLayout" checkbox in your nib/storyboard, you are using Layout, so the system adds constraints to your views if you don't.

When using AutoLayout you can't modify the frame/bounds/center of a view directly, or exactly what you describe happens. The next time something triggers a layout update, the view snaps back to the position defined by it's constraints.

You either need to turn off AutoLayout for the entire nib/storyboard, or add outlets to your constraints and change the constant value of the contstraint(s), then call layoutIfNeeded() on the view to make the constraint changes take effect.

I suggest adding outlets to the constraints. Switching to the older style struts-and-springs style form design is a big change, and one that will have large side-effects for your view controller. (Personally I prefer struts-and-springs style form design, but I force myself to use AutoLayout because that's the new way of doing things.)

Comments