动态视图的自动布局约束

时间:2015-09-30 09:40:17

标签: ios objective-c xamarin xamarin.ios autolayout

我正在为IOS创建一个自定义的uicontrol(xamarin.iOS)。 uicontrol由文本字段和按钮组成。我通过扩展UIView

创建了自定义控件

Coplexity

文本字段的宽度将由用户给出,需要在运行时呈现。

场景:用户将在应用程序中获得一个表单,他们可以在其中输入控件的宽度,例如,如果用户输入50并点击提交按钮,则在下一页中呈现自定义UIcontrol时,它应该只占整个屏幕宽度的50%。

问题

我需要为文本字段应用自动布局约束。并且我添加了约束,只有顶部和左侧约束按预期工作。当我旋转设备时,右边距不会按比例变化

this.AddConstraint (
              NSLayoutConstraint.Create(textField,NSLayoutAttribute.Left,NSLayoutRelation.Equal,this, NSLayoutAttribute.Left, 1 , 10)
        );

        this.AddConstraint (
            NSLayoutConstraint.Create(textField,NSLayoutAttribute.Right,NSLayoutRelation.Equal,this, NSLayoutAttribute.Left, 1 , ((UIScreen.MainScreen.Bounds.Width * editTextWidth)/100)+10)
        );

        this.AddConstraint (
            NSLayoutConstraint.Create( textField, NSLayoutAttribute.Top, NSLayoutRelation.Equal,label, NSLayoutAttribute.Top, 1, 30+10)
        );

        this.AddConstraint (
            NSLayoutConstraint.Create(textField, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0, 3 * 10)
        );

1 个答案:

答案 0 :(得分:1)

我不知道你是怎么用xamarin做的,但我可以解释一下如何做到这一点。

我假设您的起始x和y坐标保持不变。

然后你可以添加到开头的两个约束是:

NSLayoutConstraint.Create(textField,NSLayoutAttribute.Left,NSLayoutRelation.Equal,this, NSLayoutAttribute.Left, 1 , 10)

NSLayoutConstraint.Create( textField, NSLayoutAttribute.Top, NSLayoutRelation.Equal,label, NSLayoutAttribute.Top, 1, 30+10)

您应该添加的其他两个约束是文本字段的常量高度和宽度约束。

当视图加载时,只需更改数组中相同约束的常量,通过这样做可以简单地获得:

constraintsArray = textfield.constraints;

这会初步设定你的圣徒。

现在设置视图以侦听设备方向更改并再次更新常量:

NSNotificationCenter.DefaultCenter
                .AddObserver("UIDeviceOrientationDidChangeNotification", DeviceRotated );

    private void DeviceRotated(NSNotification notification){
        switch (UIDevice.CurrentDevice.Orientation){
        case  UIDeviceOrientation.Portrait:
            constraint.constant = ((UIScreen.MainScreen.Bounds.Width * editTextWidth)/100);
            break;
        case UIDeviceOrientation.LandscapeLeft:
        case UIDeviceOrientation.LandscapeRight:
            constraint.constant = ((UIScreen.MainScreen.Bounds.Height * editTextWidth)/100);
        }
    }
相关问题