Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to disable horizontal scroll of UIScrollView?

In UIScrollView, I have content height and width greater than scrollview's size. So basically it can scroll horizontally and vertically. What I want is to scroll vertically only and I manage horizontally scroll using an UIButton by using below code.

 [scrlViewQuestion setContentOffset:CGPointMake(questionWidth, 0) animated:YES];

Preventing horizontal scrollview, one can just set scrollview content width lesser than scrollview size but in my case scrollview content width is greater than its size? So what is the best way to solve this?

like image 862
Hiren Prajapati Avatar asked Dec 04 '17 10:12

Hiren Prajapati


2 Answers

Content UIView width should be equal to the width of UIScrollView's superview for instance, not UIScrollView itself.

enter image description here

like image 176
ManjunathK Avatar answered Oct 19 '22 15:10

ManjunathK


SWIFT 5 first, you should create a delegation class or extend the view control with UIScrollViewDelegate, and after, you should check the content offset with scrollViewDidScroll(_:) func and disable it with that: here is a sample code:

class ViewController: UIViewController {
  @IBOutlet weak var scrollView: UIScrollView!
    .
    .
    .
 override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.delegate = self 
 }
}

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

like image 2
mohsen Avatar answered Oct 19 '22 16:10

mohsen