ios - 动态 View 的自动布局约束

标签 ios objective-c xamarin xamarin.ios autolayout

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

复杂性

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

场景:用户将在应用程序中获得一个表单,他们可以在其中输入控件的宽度,例如,如果用户输入 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)
        );

最佳答案

我不知道你是如何在 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)

您应该添加的另外两个约束是文本字段的恒定高度和宽度约束。

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

constraintsArray = textfield.constraints;

这将首先设置您的约束。

现在设置您的 View 以监听设备方向变化并再次更新常量:

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

关于ios - 动态 View 的自动布局约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32862817/

相关文章:

ios - 在 Xamarin 中捕获 EXC_CRASH (SIGABRT) 异常

iOS 应用程序 : running on simulator but not building the. 应用程序

ios - 应用程序委托(delegate)或初始 View Controller ,检查用户是否通过 Firebase 登录 iOS 应用程序?

objective-c - 识别在 Swift 中的自定义 listView 单元格中按下的按钮

ios - 向后使用自定义字符串

debugging - 调试时可以写入文件而不是控制台吗?

c# - Xamarin,Grpc,无法使用 token 0100002b 解析类型

ios - iPhone 开发 - Viber 集成

ios - iOS应用因EXC_BAD_ACCESS而崩溃,异常断点未指向代码

iphone - 逐渐平稳地停止 UIImageView 动画