Setting UIScrollView Width

2019-09-09 05:57发布

问题:

I have a UIScrollView added to my ViewController. And a View on top of that Scrollview. I have done the following:

  1. Placed scroll view inside my original View and set top, left, right, and bottom constraints. Unchecking Constrain to margins.

  2. Added a UIView within the scrollView (to hold my labels and such) and added the top, left, right, and bottom constraints, constrain to margins unchecked. And set equal widths to the original View

  3. I then add an image view and three labels inside the view placed within the scroll view. And add top, left, right, bottom, and height constraints for them.

The scroll view works and my view does scroll and my labels and image view are centered but everything is very wide.

I am wondering how I make it so the View is not wide and I cannot scroll horizontally, only vertically.

回答1:

Add an equal-widths constraint between the view inside the scroll view, and the root-level view of the view controller.



回答2:

I just recently figured this out. Try doing this:

  1. Make a scroll view
  2. Put all of your labels and buttons into a stack view (If you don't know about stack views, check this out: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/
  3. Constrain the stack view's width and make sure the Allignment and Distribution are set to fill

  1. Put the Stack View inside of the scroll view
  2. Constrain the Scroll view to your hearts desire

Putting the labels and what you want in the scroll view should help with the width boundaries. Here's a picture of my successful scroll view. Hope this helps :)



回答3:

In short, the contentsize is no effect while you use autolayout.
if you want you scrollview can scroll, uou should add a container inside scrollview and add origin subviews to the container.

For example, use snapkit (maybe some typos here):

  1. you have a scrollview.set it's equal self.view's frame by autolayout
  2. [import]then you add a containerView as scrollview's subview. set contraints:

     make.edges.equalTo(scrollview) // mean its frame equal to scrollview
     make.width.equalTo(self.view)  // set width equal to self.view
     make.height.equalTo(yourheight).priorityLow()  // the actual height,if no changes,you can ingore .priorityLow()
    
  3. add your sunviews to containerView,add the contraints must set to containerView,can't set to scrollview's.forexample,:

    containerView.addSubView(myview)
    myview.snp_makeConstraints { (make) -> Void in
        make.left.equalTo(self.containerView)
        make.top.equalTo(self.containerView)
        make.right.equalTo(self.containerView)
        make.height.equalTo(267)
    }
    

Read this official doc - Technical Note TN2154 UIScrollView And Autolayout.