Ios 如何使用objective c在循环中添加约束
当在UIButton上使用“addConstraint”时,循环中的按钮x位置会出现问题Ios 如何使用objective c在循环中添加约束,ios,objective-c,autolayout,Ios,Objective C,Autolayout,当在UIButton上使用“addConstraint”时,循环中的按钮x位置会出现问题 for (int ix = 0; ix<7; ix++) { UIButton *segmentButton = [[UIButton alloc] init]; [segmentButton setTitle:[_segmentButtonTitleArray objectAtIndex:ix] forState:UIControlStateNormal];
for (int ix = 0; ix<7; ix++) {
UIButton *segmentButton = [[UIButton alloc] init];
[segmentButton setTitle:[_segmentButtonTitleArray objectAtIndex:ix] forState:UIControlStateNormal];
[_segmentView addSubview:segmentButton];
[segmentButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[_segmentView addConstraint:[NSLayoutConstraint constraintWithItem:segmentButton
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:_segmentView
attribute:NSLayoutAttributeWidth
multiplier:1.0/7
constant:0]];
[_segmentView addConstraint:[NSLayoutConstraint constraintWithItem:segmentButton
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:segmentButton.frame.size.height]];
[_segmentView addConstraint:[NSLayoutConstraint constraintWithItem:segmentButton
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:_segmentView
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:segmentButtonXposition]];
[_segmentView addConstraint:[NSLayoutConstraint constraintWithItem:segmentButton
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:_segmentView
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:segmentButton.layer.frame.origin.y]];
segmentButtonXposition = segmentButtonXposition +1+_segmentView.frame.size.width/7-1;
}
for(int ix=0;ix旋转后,它肯定会采用上一个宽度。请参见如何计算约束的left
属性值;从分段视图的
帧,旋转后不更新该帧
因此,如果我们说,对于纵向方向,您的计算结果为768/7=~109
。但是对于横向方向,此计算是不正确的,并且受到约束。常量
值应该更新为1024/7=~146
。但是您没有这样做,因此使用的是旧值
要解决这个问题,您可以在每次设备进行旋转时更新每个约束。但这将是一件乏味的事情,因为您需要为每个约束设置一个变量,然后遍历所有约束
更好的方法是使每个UILabel的宽度约束保持相等
每个标签的等宽度
label1.leading=分段视图.leading
label7.trainling=分段视图.training
标签(n).尾随=标签(n+1).前导
参考检查我的答案。通过它应用于UIScrollView
,但它将帮助您理解这一逻辑。我使用了VFL,它更加简洁。您得到了什么结果?您可以发布正在制作的图像吗?hi@GavinHope已经发布了图像。加载后即可获得结果。Bu旋转后,它会采用先前的宽度哦,所以初始加载会产生你想要的结果,但是如果你旋转设备,你会得到错误的宽度?具体来说,如果你从纵向旋转到横向,横向方向是否保持纵向中使用的宽度?直接父视图会采用设备宽度,这就是为什么initial加载对纵向或横向效果良好。一旦我从纵向旋转到横向,所有视图都会逆视图旋转,但只有此部分不起作用-请检查图像