Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable vertical scroll in UIScrollView Swift

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

like image 840
Paul Bénéteau Avatar asked Oct 04 '17 11:10

Paul Bénéteau


2 Answers

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
     }
  }
like image 123
Mr.Zyb Avatar answered Sep 17 '22 16:09

Mr.Zyb


You can simply do this. Swift 4

self.scrollView.contentSize.height = 1.0 // disable vertical scroll
like image 34
kubacizek Avatar answered Sep 19 '22 16:09

kubacizek