Forum Xamarin.iOS
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

AutoLayouts / constraints. What am I missing?

JonasRembrattJonasRembratt SEUniversity ✭✭✭
edited December 2017 in Xamarin.iOS

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?

Best Answers

  • NashZhouNashZhou USMember ✭✭✭
    Accepted Answer

    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.

  • NashZhouNashZhou USMember ✭✭✭
    edited December 2017 Accepted Answer

    @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

  • NashZhouNashZhou USMember ✭✭✭
    Accepted Answer

    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.

  • JonasRembrattJonasRembratt SEUniversity ✭✭✭
    edited December 2017

    That was it, thanks!

    What exactly is TranslatesAutoresizingMaskIntoConstraints used for?

  • NashZhouNashZhou USMember ✭✭✭
    edited December 2017 Accepted Answer

    @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.

  • JonasRembrattJonasRembratt SEUniversity ✭✭✭

    Yup. That helped. Thanks Nash!

Sign In or Register to comment.