On VisualStudio I am trying to display a button in my custom 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();
}
}
}
When trying to run this the app crashes and gives me this: Full message here
I would appreciate the help in figuring out how to resolve this and what specifically I am doing wrong. I don't like using storyboards and prefer to do things programatically. I haven't been able to find a thread with this specific problem. Maybe it's obvious and I'm just not aware.
You need to add the button to the View before you set the constraint. When it tries to set up the constraint, the button has not been added to the view hierarchy yet so it cannot set it up correctly.
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;
}