在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;
}