Add scrollable button to scrollview Add scrollable button to scrollview swift swift

Add scrollable button to scrollview


func setContentOffset(scrollView: UIScrollView) {        let numOfItems = itemCount  // 5    let stopOver = scrollView.contentSize.width / CGFloat(numOfItems)    let x = round(scrollView.contentOffset.x / stopOver) * stopOver        guard x >= 0 && x <= scrollView.contentSize.width - scrollView.frame.width else {        return    }        scrollView.setContentOffset(CGPointMake(x, scrollView.contentOffset.y), animated: true)}

extension ViewController: UIScrollViewDelegate {    func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {            setContentOffset(scrollView)    }    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {            guard !decelerate else {            return        }            setContentOffset(scrollView)    }}

Also made a demo project in Github
https://github.com/rishi420/ScrollViewCustomPaging


Update:

Trying to consider for the scrolling velocity when user endDragging.

var velocityX = CGFloat(0.0) 

.

func setContentOffset(scrollView: UIScrollView) {        let numOfItems = itemCount    let stopOver = scrollView.contentSize.width / CGFloat(numOfItems)    var x = round((scrollView.contentOffset.x + (velocityX * 150)) / stopOver) * stopOver // 150 is for test. Change it for your liking        x = max(0, min(x, scrollView.contentSize.width - scrollView.frame.width))        scrollView.setContentOffset(CGPointMake(x, scrollView.contentOffset.y), animated: true)}

.

func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>){    velocityX = velocity.x}


Have you tried using a UITableView instead of UIScrollView and making the tableview's size equal to size of button you want. Then add the button to its cell.Enable the UITableView's "Paging"

This will help you better to manage content i.e. buttons more conveniently as you are can pass the array of buttons to the tableview and manage in its cellForAtIndex method.


After you calculate the button index in your scrollViewDidEndDecelerating() method, simply call scrollRectToVisible(rect, animated:) with the frame of the button at that index.