简体   繁体   中英

iOS How to auto layout a view 3 x screen width?

I tried to place a UIView which is 3x the screen width (or 3x UIScrollView 's width) in UIScrollView .

UIScrollView 's width equal to the screen width.

How do I do this in AutoLayout?

Assign a value for your views's width constraint and make an IBOutlet for this in your header file.

In your m file's viewDidLoad method get the width of the current device's screen, multiply by 3 and assign to your constraint's constant. And finally call your view's layoutIfNeeded method.

Is this clear enough or do you want me to make it more clear?

If you want to do it in code via pure AutoLayout, here's how you'd do it:

- (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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM