我正在尝试创建一个UIViewController,它具有两个垂直堆叠在UIView底部的按钮(就像iPod上的iOS操作表一样)。出于某种原因,我的顶部按钮的顶部锚点始终固定在UIViewController的顶部。
我已经有了底部按钮,可以移动到控制器底部的正确位置。我是通过这样设置第二个按钮的顶部锚点来实现的:
NSLayoutConstraint.ActivateConstraints(new[] { this.secondButton.TopAnchor.ConstraintEqualTo(this.View.SafeAreaLayoutGuide.BottomAnchor, -(this.secondButton.Frame.Height + 30f)) });
this.secondButton.UpdateConstraints();
我也尝试对第一个按钮做类似的事情。我经历了2种情况,其中顶部按钮被固定在顶部。
使用与设置第二个按钮相同的逻辑类型设置顶部锚点
NSLayoutConstraint.ActivateConstraints(new[] {
this.firstButton.HeightAnchor.ConstraintEqualTo(this.firstButton.Frame.Height),
this.firstButton.TopAnchor.ConstraintEqualTo(this.View.SafeAreaLayoutGuide.BottomAnchor, -(2 * this.secondButton.Frame.Height + 60f)) });
this.firstButton.UpdateConstraints();
结果:
通过将上面的TopAnchor行交换到此按钮,基于按钮2设置底部锚点
this.firstButton.BottomAnchor.ConstraintEqualTo(this.buttonTwo.TopAnchor, -30f)
不管我如何为按钮一设置高度锚和顶部/底部锚,它都不会停止锚定到视图控制器的最顶部。我确保两个按钮的TranslatesAutoresizingMaskIntoConstraints都设置为false,并且我检查了这两个按钮上是否没有约束。有见识吗?谢谢!
我们需要查看您项目中的所有约束,以找出原因和解决方案。我想您在添加新约束时不会删除旧约束。
我给您写了一个示例,修复了底部的两个按钮:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
UIButton firstButton = new UIButton(UIButtonType.System);
firstButton.SetTitle("first", UIControlState.Normal);
firstButton.Layer.BorderColor = UIColor.Green.CGColor;
firstButton.Layer.BorderWidth = 1.5f;
View.Add(firstButton);
UIButton secondButton = new UIButton(UIButtonType.System);
secondButton.SetTitle("second", UIControlState.Normal);
secondButton.SetTitleColor(UIColor.Red,UIControlState.Normal);
secondButton.Layer.BorderColor = UIColor.Yellow.CGColor;
secondButton.Layer.BorderWidth = 1.50f;
View.Add(secondButton);
firstButton.TranslatesAutoresizingMaskIntoConstraints = false;
secondButton.TranslatesAutoresizingMaskIntoConstraints = false;
View.AddConstraints(new[] {
secondButton.HeightAnchor.ConstraintEqualTo(60),
secondButton.BottomAnchor.ConstraintEqualTo(this.View.SafeAreaLayoutGuide.BottomAnchor,0),
secondButton.LeftAnchor.ConstraintEqualTo(View.LeftAnchor,20),
secondButton.RightAnchor.ConstraintEqualTo(View.RightAnchor,-20),
});
View.AddConstraints(new[] {
firstButton.HeightAnchor.ConstraintEqualTo(60),
firstButton.BottomAnchor.ConstraintEqualTo(secondButton.TopAnchor,-30),
firstButton.LeftAnchor.ConstraintEqualTo(View.LeftAnchor,20),
firstButton.RightAnchor.ConstraintEqualTo(View.RightAnchor,-20),
});
}
这是结果: