我有这个带约束的配置,我可以看到字段,但是当我旋转屏幕时,一切都不见了,我什么也看不到
public override void ViewDidLoad()
{
field1.Frame = new CoreGraphics.CGRect(10, 10, 100, 20);
field2.Frame = new CoreGraphics.CGRect(10, 50, 100, 20);
field1.TranslatesAutoresizingMaskIntoConstraints = false;
field2.TranslatesAutoresizingMaskIntoConstraints = false;
View.AddConstraints(new[] {
NSLayoutConstraint.Create(field1, NSLayoutAttribute.Width, NSLayoutRelation.Equal, View, NSLayoutAttribute.Width, 1, -200),
NSLayoutConstraint.Create(field1, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1, 40),
NSLayoutConstraint.Create(field1, NSLayoutAttribute.Top , NSLayoutRelation.Equal, View, NSLayoutAttribute.Top, 1, View.Bounds.Size.Height/2),
NSLayoutConstraint.Create(field1, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterX, 1, 0)
});
View.AddConstraints(new[] {
NSLayoutConstraint.Create(field2, NSLayoutAttribute.Width, NSLayoutRelation.Equal, field1, NSLayoutAttribute.Width, 1, 0),
NSLayoutConstraint.Create(field2, NSLayoutAttribute.Height, NSLayoutRelation.Equal, field1, NSLayoutAttribute.Height, 1, 0),
NSLayoutConstraint.Create(field2, NSLayoutAttribute.Top, NSLayoutRelation.Equal, field1, NSLayoutAttribute.Bottom, 1, 10),
NSLayoutConstraint.Create(field2, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterX, 1, 0)
});
}
但是当我旋转我的手机屏幕时,这个配置不起作用,我看不到文本字段,我该如何解决这个错误?
最佳答案
问题是由以下原因引起的:
NSLayoutConstraint.Create(field1, NSLayoutAttribute.Top , NSLayoutRelation.Equal, View, NSLayoutAttribute.Top, 1, View.Bounds.Size.Height/2),
一旦您设置了 View.Bounds.Size.Height/2
,它就是一个常量,不会在您旋转屏幕后更新。
所以最简单的解决方案是将其更改为:
NSLayoutConstraint.Create(field1, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterY, 1, -20),
或者您可以在旋转后更新约束。
关于c# - 旋转屏幕时的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59149219/