How to disable horizontal scrolling of UIScrollView?

前端 未结 14 1659
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 08:17

I have a UIView like iPhone\'s Springboard. I have created it using a UIScrollView and UIButtons. I want to disable horizontal scrolli

相关标签:
14条回答
  • 2020-12-02 08:39

    Disable horizontal scrolling by overriding contentOffset property in subclass.

    override var contentOffset: CGPoint {
      get {
        return super.contentOffset
      }
      set {
        super.contentOffset = CGPoint(x: 0, y: newValue.y)
      }
    }
    
    0 讨论(0)
  • 2020-12-02 08:41

    You have to set the contentSize property of the UIScrollView. For example, if your UIScrollView is 320 pixels wide (the width of the screen), then you could do this:

    CGSize scrollableSize = CGSizeMake(320, myScrollableHeight);
    [myScrollView setContentSize:scrollableSize];
    

    The UIScrollView will then only scroll vertically, because it can already display everything horizontally.

    0 讨论(0)
  • 2020-12-02 08:41

    In my case, with Swift 4.2 you can use:

    Disable vertical scroll:

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.contentOffset.y = 0.0
    }
    

    Disable horizontal scroll:

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.contentOffset.x = 0.0
    }
    
    0 讨论(0)
  • 2020-12-02 08:45

    I had the tableview contentInset set in viewDidLoad (as below) that what causing the horizontal scrolling

    self.tableView.contentInset = UIEdgeInsetsMake(0, 30, 0, 0);
    

    Check if there are any tableview contentInset set for different reasons and disable it

    0 讨论(0)
  • 2020-12-02 08:49

    Try This:

    CGSize scrollSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, scrollHeight);
    [scrollView setContentSize: scrollSize];
    
    0 讨论(0)
  • 2020-12-02 08:51

    In my case the width of the contentView was greater than the width of UIScrollView and that was the reason for unwanted horizontal scrolling. I solved it by setting the width of contentView equal to width of UIScrollView.

    Hope it helps someone

    0 讨论(0)
提交回复
热议问题