Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling Horizontal Scrolling from UIScrollView Swift

Scroll View

I have a UIScrollView, with constraints left: 0, top: 0, right: 0, bottom: 0

Inside Scroll View

At the top of this UIScrollView is a UIImageView with constraints left: 0, top: 0, right: 0, height: 200

Underneath this I have a UITextView with constraints left: 0, top: 0, right: 0, bottom: 0

This means the UITextView will resize with respect to its content, and I set the scrollingEnabled to false for the UITextView.

So, when I run, it almost works perfectly.

The one problem is the UIImageView takes up about 10% more than the actual screen width. Hence, horizontal scrolling is enabled.

I have tried adding the lines

imageView.frame = CGRect(0, 0, screenSize.width, 200) scrlView.contentSize.width = screenSize.width 

but this makes no difference. I can still scroll horizontally and the Image View still takes up around 10% more than the actual screen width.

Note, I have not set imageView screen width in storyboard, only programatically.

Any ideas?

like image 539
Greg Peckory Avatar asked Aug 25 '15 07:08

Greg Peckory


People also ask

How do I stop horizontal scrollbar?

To hide the horizontal scrollbar and prevent horizontal scrolling, use overflow-x: hidden: HTML.

How do I stop horizontal scrolling in web design?

You can also set the overflow-x CSS property to hidden, which prevents child content from wrapping within its container but turns off sideways scrolling. Another solution is to set the width of child elements to 100%.


2 Answers

Like this,

Swift 4.0

func scrollViewDidScroll(scrollView: UIScrollView) {     if scrollView.contentOffset.x>0 {         scrollView.contentOffset.x = 0     } } 

And, you can set this property:

scrollImg.isDirectionalLockEnabled = true 
like image 129
Larry Pickles Avatar answered Sep 20 '22 20:09

Larry Pickles


Swift 4

Horizontal Scroll Lock

func scrollViewDidScroll(_ scrollView: UIScrollView) {     if scrollView.contentOffset.x != 0 {         scrollView.contentOffset.x = 0     } } 

You can change the x to y for vertical scrolling.

Make sure to add UIScrollViewDelegate like this:

class MyViewController: UIViewController, UIScrollViewDelegate {      @IBOutlet var scrollView: UIScrollView!      ... } 

And set the delegate for the ScrollView

scrollView.delegate = self 
like image 28
Hunter Copp Avatar answered Sep 23 '22 20:09

Hunter Copp