Search code examples
c#xamarinuiviewconstraintsvisual-studio-mac

Xamarin and ios Anchor Constraints not working


If I add this code to the ViewDidLoad of the basic startup project the red view is nowhere to be seen... I think it should show at the top center of the window... what am I doing wrong?

        var redview = new UIView(new CGRect(0, 0, 100, 200));
        redview.BackgroundColor = UIColor.Red;
        redview.TranslatesAutoresizingMaskIntoConstraints = false;
        View.AddSubview(redview);

        redview.TopAnchor.ConstraintEqualTo(this.View.TopAnchor).Active = true;
        redview.CenterXAnchor.ConstraintEqualTo(this.View.CenterXAnchor).Active = true;

Solution

  • Because you have set the frame of the redView.which will be in conflict with Constraint. Refer to the following code

    var redview = new UIView();
    redview.BackgroundColor = UIColor.Red;
    redview.TranslatesAutoresizingMaskIntoConstraints = false;
    View.AddSubview(redview);
    
    redview.TopAnchor.ConstraintEqualTo(this.View.TopAnchor).Active = true;
    redview.CenterXAnchor.ConstraintEqualTo(this.View.CenterXAnchor).Active = true;
    redview.WidthAnchor.ConstraintEqualTo(100).Active=true;
    redview.HeightAnchor.ConstraintEqualTo(200).Active = true;