Xamarin 和没有界面生成器的自动布局

本文关键字:自动布局 界面 Xamarin | 更新日期: 2023-09-27 18:31:56

好的,我看到了另一个问题,他们建议使用FluentLayouts,但我想在没有约束的情况下做到这一点。所以问题是这样的:我已经创建了带有导航栏和选项卡栏的应用程序,现在我正在尝试插入 MyViewController 2 个按钮,其中一个位于中间(我发布的代码)和导航栏下方的右侧。

//------Appdelegate.cs
   myViewController = new MyViewController ();
   UINavigationController myNavController = new UINavigationController (myViewController);
   window.RootViewController = myNavController;
//-----MyViewController
public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
            button1.SetTitle("Button1", UIControlState.Normal);
            button1.BackgroundColor = UIColor.Red;
            button2.SetTitle("Button2", UIControlState.Normal);
            button2.BackgroundColor = UIColor.Gray;
            View.AddSubview (button1);
            View.AddSubview (button2);
            View.AddConstraint (NSLayoutConstraint.Create (button1, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, View,NSLayoutAttribute.CenterX, 1, 0));
            View.AddConstraint (NSLayoutConstraint.Create (button1, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, View,NSLayoutAttribute.CenterY, 1, 0));
}

使用此代码,button1 根本没有出现,因为它位于 (0,0) 我不知道为什么,有人可以给我一个提示吗? 另一个问题是我不知道如何获取导航栏的 bottow 值,所以我可以将 button2 放在那里。我关注了这篇文章。

Xamarin 和没有界面生成器的自动布局

你应该做这样的事情:

 button1.TranslatesAutoresizingMaskIntoConstraints = false;
 button2.TranslatesAutoresizingMaskIntoConstraints = false;

因此,您可以使用约束,否则它们将被自动调整大小掩码覆盖。你也不应该使用

EdgesForExtendedLayout = UIRectEdge.None;

我认为最后一行的按钮位置错误