iOS如何自动布局视图3 x屏幕宽度?

时间:2015-01-28 17:41:57

标签: ios uiscrollview autolayout

我尝试在UIView中放置一个UIScrollView,它是屏幕宽度的3倍(或3x UIScrollView的宽度)。

UIScrollView的宽度等于屏幕宽度。

如何在AutoLayout中执行此操作?

2 个答案:

答案 0 :(得分:0)

为视图的宽度约束指定一个值,并在头文件中为此创建一个IBOutlet。

在m文件的viewDidLoad方法中,获取当前设备屏幕的宽度,乘以3并分配给约束的常量。最后调用视图的layoutIfNeeded方法。

这是否足够明确,或者您是否希望我更清楚?

答案 1 :(得分:0)

如果您想通过纯AutoLayout在代码中执行此操作,请按以下步骤操作:

- (void)layoutUserInterface {
    // Placing the scrollView using AutoLayout
    [self.view addSubview:self.scrollView];
    // Note: The "H:" is optional, but I like to be clear
    [self.view addConstraints:
     [NSLayoutConstraint
      constraintsWithVisualFormat:@"H:|[scrollview]|"
      options:0
      metrics:nil
      views:@{@"scrollview": self.scrollView}]];
    [self.view  addConstraints:
     [NSLayoutConstraint
      constraintsWithVisualFormat:@"V:|[scrollview]|"
      options:0
      metrics:nil
      views:@{@"scrollview": self.scrollView}]];

    // Placing the "wideView" using AutoLayout
    [self.scrollView addConstraints:
     [NSLayoutConstraint
      constraintsWithVisualFormat:@"H:|[wideView]"
      options:0
      metrics:nil
      views:@{@"wideView": self.wideView}]];
    [self.scrollView addConstraints:
     [NSLayoutConstraint
      constraintsWithVisualFormat:@"V:|[wideView]"
      options:0
      metrics:nil
      views:@{@"wideView": self.wideView}]];
    // Setting up the 3x width constraint
    [self.scrollView addConstraint:
     [NSLayoutConstraint
      constraintWithItem:self.wideView
      attribute:NSLayoutAttributeWidth
      relatedBy:NSLayoutRelationEqual
      toItem:self.view
      attribute:NSLayoutAttributeWidth
      multiplier:3.0f
      constant:0.0f]];
    // Figure out your "wideView's" height requirements

}