Stopping ScrollView Going Above & Below The Bounds

2019-08-01 13:46发布

问题:

I created a UIScrollView in a ViewController and added UIView & UITableView as siblings of ViewController.

 var pageSize = view.bounds.size

 // MiniQuestion: I disabled vertical indicators but it caused a gap for the width
 // of the indicator, so I added the gap manually. Is it okay behaviour?
 pageSize.width += 5


 MyView.backgroundColor = UIColor.redColor()
 MyTableView.backgroundColor = UIColor.blueColor()

 let pagesViews = [MyView , MyTableView]
 let numberOfPages = pagesViews.count

 for (pageIndex,page) in pagesViews.enumerate(){
    page.frame = CGRect(origin: CGPoint(x:0 , y:CGFloat(pageIndex) * pageSize.height), size: pageSize)
    ScrollView.addSubview(page)
 }

 ScrollView.contentSize = CGSize(width: pageSize.width, height: pageSize.height * CGFloat(numberOfPages))

It's working nice. Except, even though I have 2 pages and added constraints to ScrollView, it's going above the top page (when I pull more) and below the end of tableview page (when I push more). However I want to scroll it until the end of the tableview and stuck at the bound of the top.

Normally they look fine... However,

If I pull beyond top:

If I push below bottom:

How can I prevent this behaviour?

回答1:

If you don't want to enable user to pull it beyond the bounds of scroll view then:

ScrollView.bounces = false