OGeek|极客世界-中国程序员成长平台

标题: ios - 使用自动布局以编程方式将 subview 添加到 UIView 时出现错误的来源 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 20:06
标题: ios - 使用自动布局以编程方式将 subview 添加到 UIView 时出现错误的来源

我有一个 UIView 子类,我在其中以编程方式创建和添加一些 subview 。确切地说,我有 6 个 subview 水平对齐,彼此相邻,它们之间的空间为零。侧边距(即从我的 View 左边框到第一个 subview 的距离以及从最后一个 subview 到我的 View 右边框的距离)必须为​​ 16pt,并且剩余空间必须在 subview 之间平均分配。它应该是这样的:

enter image description here

我正在尝试使用这样的自动布局来完成此操作:

NSDictionary *viewsDict = @{@"digit1":digit1, @"digit2":digit2, @"digit3":digit3, @"digit4":digit4, @"digit5":digit5, @"digit6":digit6};
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"H:|-16-[digit1][digit2(==digit1)][digit3(==digit1)][digit4(==digit1)][digit5(==digit1)][digit6(==digit1)]-16-|" options:0 metrics:nil views:viewsDict]];

当我在具有 320pt 屏幕 View 的 iPhone 5 上运行此程序时,我期望得到以下结果:

subview 宽度320 - 2*16)/6 = 48

所以框架应该是:

digit1: x =  16, width = 48
digit2: x =  64, width = 48
digit3: x = 112, width = 48
digit4: x = 160, width = 48
digit5: x = 208, width = 48
digit6: x = 256, width = 48

但是,在运行时会发生一件奇怪的事情:我的边距是错误的:

enter image description here

我得到的 subview 框架是这些:

digit1: x =  21, width = 48
digit2: x =  66, width = 48
digit3: x = 111, width = 48
digit4: x = 156, width = 48
digit5: x = 201, width = 48
digit6: x = 246, width = 48

所以我的左边距是 21pt,右边是 26pt。此外, subview 重叠 3pt。

我已经用 Reveal 检查了 View 层次结构,我可以确认 有一个正确的常数为 16 的边距约束。但由于某种原因,框架有所不同。似乎也没有任何其他冲突的约束,我在运行应用程序时也没有收到自动布局错误。

谁能看到我在这里遗漏了什么?

编辑:

使用间隔 View 而不是间距限制来测试 Aloks 建议我尝试了这个:

UIView *spacer1 = [[UIView alloc] init];
UIView *spacer2 = [[UIView alloc] init];
spacer1.translatesAutoresizingMaskIntoConstraints = NO;
spacer2.translatesAutoresizingMaskIntoConstraints = NO;
spacer1.backgroundColor = [UIColor redColor];
spacer2.backgroundColor = [UIColor redColor];
[self addSubview:spacer1];
[self addSubview:spacer2];
NSDictionary *viewsDict = @{@"spacer1":spacer1, @"digit1":digit1, @"digit2":digit2, @"digit3":digit3, @"digit4":digit4, @"digit5":digit5, @"digit6":digit6, @"spacer2":spacer2};
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"H:|[spacer1(16)][digit1][digit2(==digit1)][digit3(==digit1)][digit4(==digit1)][digit5(==digit1)][digit6(==digit1)][spacer2(16)]|" options:0 metrics:nil views:viewsDict]];

这给了我以下结果:

enter image description here

如您所见,间隔 View 的位置正确,但数字 subview 仍保留在原来的位置。



Best Answer-推荐答案


你的约束应该是这样的:

等宽到每个 View 彼此

固定高度到每个 View

前导、尾随和顶部或底部(合适)到每个 View 。

它会正常工作

查看此约束的输出

enter image description here

你只需要把它转换成代码!!!!

如果您以编程方式添加 View ,那么如何设置 View 的框架也很重要。根据屏幕尺寸,您的框架应该是动态的。

希望这会有所帮助

关于ios - 使用自动布局以编程方式将 subview 添加到 UIView 时出现错误的来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37322384/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4