首页 文章

动态视图的自动布局约束

提问于
浏览
0

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

Coplexity

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

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

Issue

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

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 回答

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

    这将最初设置你的constaints .

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

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

相关问题