Xamarin 和 ios 锚点约束不起作用

Xamarin and ios Anchor Constraints not working

如果我将此代码添加到基本启动项目的 ViewDidLoad 中,红色视图将无处可见...我认为它应该显示在 window 的顶部中心...这是什么我做错了吗?

        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;

因为你设置了redView的框架,会和Constraint冲突。 参考以下代码

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;