I want to center an image inside of a view, using iOS AutoLayout. This is my code ...
public void AddImage(UIView view, string imageName) { var image = UIImage.FromBundle(imageName); var imageView = new UIImageView(image); view.AddSubview(imageView); NSLayoutConstraint.Create(imageView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, view, NSLayoutAttribute.CenterX, 1f, 0f).Active = true; NSLayoutConstraint.Create(imageView, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, view, NSLayoutAttribute.CenterY, 1f, 0f).Active = true; }
... and it has zero effect (the image ends up in the top left corner of view
).
Am I missing some crucial/basic step somewhere?
Yes @JonasRembratt, you're not turning TranslatesAutoresizingMaskIntoConstraints
to false for your imageView variable. The default value is true unless you set it to false or if you use the storyboard.
Once you do that, your constraints should work.
@JonasRembratt From my understanding, iOS creates constraints for you when you set things like the Frame
on a view. Autoresizing is technically the "old" way developers coded layouts. When you use AutoLayout you want to tell iOS you'll handle the constraints so you set this property to false.
Hope that helps, and it's a common problem for a lot of people.
Answers
Yes @JonasRembratt, you're not turning
TranslatesAutoresizingMaskIntoConstraints
to false for your imageView variable. The default value is true unless you set it to false or if you use the storyboard.Once you do that, your constraints should work.
That was it, thanks!
What exactly is
TranslatesAutoresizingMaskIntoConstraints
used for?@JonasRembratt From my understanding, iOS creates constraints for you when you set things like the
Frame
on a view. Autoresizing is technically the "old" way developers coded layouts. When you use AutoLayout you want to tell iOS you'll handle the constraints so you set this property to false.Hope that helps, and it's a common problem for a lot of people.
Yup. That helped. Thanks Nash!