locked
AutoLayouts / constraints. What am I missing? RRS feed

  • Question

  • User26493 posted

    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?

    Friday, December 15, 2017 4:09 PM

Answers

  • User272135 posted

    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.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Saturday, December 16, 2017 3:19 AM
  • User272135 posted

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

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Saturday, December 16, 2017 3:11 PM

All replies

  • User272135 posted

    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.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Saturday, December 16, 2017 3:19 AM
  • User26493 posted

    That was it, thanks!

    What exactly is TranslatesAutoresizingMaskIntoConstraints used for?

    Saturday, December 16, 2017 2:51 PM
  • User272135 posted

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

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Saturday, December 16, 2017 3:11 PM
  • User26493 posted

    Yup. That helped. Thanks Nash!

    Sunday, December 17, 2017 9:36 AM