C# 无法在 VisualStudio 上对 iOS 应用程序的按钮使用约束

C# Unable to use constraints on button for iOS app on VisualStudio

在 VisualStudio 上,我试图在我的自定义中显示一个按钮 ViewController:

using System;
using UIKit;

namespace Playground
{
  public class CustomViewController: UIViewController
  {
    public CustomViewController()
    {
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        UIButton button = UIButton.FromType(UIButtonType.System);

        button.TranslatesAutoresizingMaskIntoConstraints = false;
        button.SetTitle("Click", UIControlState.Normal);

        button.CenterXAnchor.ConstraintEqualTo(View.CenterXAnchor).Active = true;
        button.CenterYAnchor.ConstraintEqualTo(View.CenterYAnchor).Active = true;
        button.WidthAnchor.ConstraintEqualTo(View.WidthAnchor).Active = true;
        button.HeightAnchor.ConstraintEqualTo(20).Active = true;


        View.AddSubview(button);
    }

    public override void DidReceiveMemoryWarning()
    {
        base.DidReceiveMemoryWarning();
    }
  }
}

当尝试 运行 这个应用程序崩溃并给我这个:Full message here

如果您能帮助我找出解决方法以及具体我做错了什么,我将不胜感激。我不喜欢使用故事板,更喜欢以编程方式做事。我一直无法找到这个特定问题的线程。也许这很明显,我只是不知道。

您需要在设置约束之前将按钮添加到视图。当它尝试设置约束时,按钮尚未添加到视图层次结构中,因此无法正确设置它。

public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        UIButton button = UIButton.FromType(UIButtonType.System);

        button.TranslatesAutoresizingMaskIntoConstraints = false;
        button.SetTitle("Click", UIControlState.Normal);

        View.AddSubview(button);

        button.CenterXAnchor.ConstraintEqualTo(View.CenterXAnchor).Active = true;
        button.CenterYAnchor.ConstraintEqualTo(View.CenterYAnchor).Active = true;
        button.WidthAnchor.ConstraintEqualTo(View.WidthAnchor).Active = true;
        button.HeightAnchor.ConstraintEqualTo(20).Active = true;
    }