How to move a UIView programmatically in Swift

iKK picture iKK · Jun 13, 2015 · Viewed 25.7k times · Source

The issue is to move an "InfoView" (UIView) programmatically in Swift.

The following constraints exist in the storyboard (see image):

enter image description here

Now, I would like to move the "InfoView" inside "MyView" up or down.

I tried:

@IBOutlet weak var infoTextLabel: UILabel!
@IBOutlet weak var infoTextLabelView: UIView!

// set infoTextLabel color
self.infoTextLabel.textColor = UIColor.blackColor()
// set infoTextLabel text
self.infoTextLabel.text = "hello"
// unhide infoTextLabel
self.infoTextLabel.hidden = false

// For the moving in Y-direction, I tried this - but does not work !!!!!!!
self.infoTextLabelView.frame.origin.y += 200

Could the Autolayout-constraints play a role. How to overcome those programmatically. Or is the frame.origin.y method the wrong one ??

Appreciate any help on this !

Answer

Darren Findlay picture Darren Findlay · Jun 14, 2015

When using constraints, you never want to set a view's frame directly. Instead, reconfigure the constraints and let the auto layout engine set your view's frame for you. Create an IBOutlet in your view controller to store a reference to your "Center Y Alignment constraint". Make sure you connect it in your storyboard or xib.

@IBOutlet var yConstraint: NSLayoutConstraint

Then you can set the constraint's constant property to offset it from the Y position (positive number will move it down, negative moves it up).

yConstraint.constant = 200

This would move your view 200 points down.