Disable vertical scroll in UIScrollView Swift

2020-06-13 16:05发布

问题:

(Don't mark this question as duplicated. I read a lot of questions but I don't find the answer to my issue.)

My issue is the following: I have a UIScrollView which is supposed to only scroll horizontally. Here it scrolls vertically for 20px (strange fact: it appears to be the same height of the status bar).

I tried to print the content size, the y offset and the height of the UIScrollView like this:

print(horizontalScrollView.contentSize)
print(horizontalScrollView.bounds.size.height)
print(horizontalScrollView.contentOffset.y)

I get this:

(1125.0, 667.0). // scrollview content size
667.0.           // scrollview height
-20.0            // content offset (y)

I know that the scrollView content size height must be <= scrollView height. And as you can see this is the case.

I use constraints to put 3 UIViewController stacked horizontally. And it works well except of this issue.

Another fact: It worked before Swift 4 and Xcode 9... I don't know if this could be the cause or not.

Do you have some ideas? Thanks in advance for your help.

回答1:

in Swift 4 and Xcode 9 content insets can get adjusted automatically. Try setting your scrollview's behaviour to not adjust it.

if #available(iOS 11, *) {
    scrollview.contentInsetAdjustmentBehavior = .never
}


回答2:

You can simply do this. Swift 4

self.scrollView.contentSize.height = 1.0 // disable vertical scroll


回答3:

very charm solution is:

     // also don't forget
     // YourViewController: UIViewController, UIScrollViewDelegate {

  @IBOutlet weak var scrollView: UIScrollView!

  override func viewDidLoad() {
    super.viewDidLoad()

    self.scrollView.delegate = self
  }

  func scrollViewDidScroll(_ scrollView: UIScrollView) {
     if scrollView.contentOffset.y > 0 || scrollView.contentOffset.y < 0 {
        scrollView.contentOffset.y = 0
     }
  }


回答4:

just set the contentOffset in scrollViewDidScroll

if scrollView.contentOffset.y > 0 {
    scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0)
}


回答5:

Use next class, setting canScroll as needed:

class BlockScrollView: UIScrollView {
    var canScroll = true

    override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
        if canScroll {
            super.setContentOffset(contentOffset, animated: animated)
        }
    }
}


回答6:

just add single Line

yourScrollView.bounces = false

and make Sure your scroll view subview(Content) height is equal to you scrollview height And you're Done