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

标签 c# ios constraints anchor visual-studio-mac

在 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

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

最佳答案

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

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

关于C# 无法在 VisualStudio 上对 iOS 应用程序的按钮使用约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48200671/

相关文章:

c# - 使用 'var'会影响性能吗?

ios - 如何将物理主体作为子级添加到 SKSpriteNode?

ios - 使用自动布局将 View 定位在主页按钮一侧

ios - 如何保持 View 最大宽度,直到前导/尾随尺寸变得太小?

c# - DTSearch COM Interop - 如何向 C# 公开对象?

c# - 在 HTTP GET 中绑定(bind) en-GB 日期

ios - 使用自动布局将 subview 尾端与 super View 中心 X 轴对齐

ios - 触摸对象GLKIT或OpenGL有什么功能?

python - SQLAlchemy 不会在 MySQL [Debian Linux] 上创建外键

c# - 使用 API 连接到远程 mysql 数据库