2016-02-04 45 views
0

添加约束环路而在循环问题使用“addConstraint”上的UIButton与按钮x位置来了,如何使用目标C

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

一个期望的结果是这样,但无法产生结果。

Desired Result

+0

你会得到什么结果?你可以发布正在制作的图片吗? –

+0

hi @GavinHope已经发布了图片http://i.stack.imgur.com/bewjn.png。加载后获取结果。但是在旋转之后,它的宽度为 –

+0

哦,所以初始加载会产生你想要的结果,但是如果你旋转设备,你会得到错误的宽度?具体来说,如果从** portrait **旋转到** landscape **,横向是否保留纵向使用的* width *? –

回答

0

它肯定会旋转后采取先前的宽度。了解如何计算约束的left属性值;来自segmentVIew's的帧,您在旋转之后没有更新。

所以,如果我们说肖像取向你的计算来作为768/7 = ~109。但是,对于横向方向,此计算结果不正确,并且constraint.constant值应更新为1024/7 = ~146。但你没有这样做,所以旧的价值正在被采纳。

要解决此问题,可以在每次设备旋转时更新每个约束。但是,这将是乏味的,因为你需要为每个约束有一个变量,然后遍历所有的约束。

更好的方法是保持每个UILabel的宽度相等。

  1. EqualWidth每个拉布勒
  2. label1.leading = segmentView.leading
  3. label7.trainling = segmentView.trailing
  4. 标签(n)的.trailing =标签(N + 1).leading

仅供参考,请查看我的回答here。通过它应用于UIScrollView,但它会帮助你理解这个逻辑。我已经使用VFL来更简洁。