Search code examples
iosxamarin.iosnslayoutconstraint

How do I align my control using programmed constraints


What I am trying to accomplish is fairly simple in the storyboard, but I couldn't get it to work through code only - which is necessary for my particular problem.

My code:

        scrollView.TopAnchor.ConstraintEqualTo(this.View.TopAnchor, 50).Active = true;
        scrollView.BottomAnchor.ConstraintEqualTo(this.View.BottomAnchor, 50).Active = true;
        scrollView.LeftAnchor.ConstraintEqualTo(this.View.LeftAnchor, 50).Active = true;
        scrollView.RightAnchor.ConstraintEqualTo(this.View.RightAnchor, 50).Active = true;
        scrollView.BackgroundColor = UIColor.Black;

        View.AddSubview(scrollView);

What I am trying to do:

In the end I want to position myself inbetween what resembles the Top+Bottom Layout guides in the storyboard - the code does not reflect this. I used this.Top(/Bottom)LayoutGuide, which essentially produced the same error.

Why do I want to do this?

My layout needs to adapt to orientation changes - constraints seem to be the way to go there. Using the layout guides seems to be working in the storyboard too somehow - so it must be doable in code too? Also right now the navigation + tab bars both overlaw the scroll bar.

I'm getting this error message:

(this might help people who come here from google because of a similar issue)

Foundation.MonoTouchException: Objective-C exception thrown.  Name: NSGenericException Reason: Unable to activate 
constraint with anchors <NSLayoutYAxisAnchor:0x174274080 "UIScrollView:0x102245400.top"> and 
<NSLayoutYAxisAnchor:0x1702707c0 "UIView:0x10135e760.top"> because they have no common ancestor.  
Does the constraint or its anchors reference items in different view hierarchies?  That's illegal. ...

If someone would be kind enough to push me into the right direction I would very much appreciate it. I can't seem to find the correct anchor to pass to the constraint yet.


Solution

  • You have to add subview first. Then you can add constraints. It is also necesarry to set translatesAutoresizingMaskIntoConstraints to false.

    scrollView.translatesAutoresizingMaskIntoConstraints = false;
    View.AddSubview(scrollView);
    scrollView.TopAnchor.ConstraintEqualTo(this.View.TopAnchor, 50).Active = true;     
    scrollView.BottomAnchor.ConstraintEqualTo(this.View.BottomAnchor, 50).Active = true; 
    scrollView.LeftAnchor.ConstraintEqualTo(this.View.LeftAnchor, 50).Active = true; 
    scrollView.RightAnchor.ConstraintEqualTo(this.View.RightAnchor, 50).Active = true;