Reputation: 41
To Scroll 2 different scrollView together, Many questions have been already answered regarding using the scrollViewDidScroll Method and passing the content offset of one scrollview to other.
But My Question here is a bit different, Let’s say I have 2 ScrollView A and B both with horizontal scrolling only.
When the view loads ScrollView A has contentOffSet say (x,y) and B scrollview’s content offset : (m,n).
As per my understanding content Offset is the new (x,y) value while scrolling.
Now I can’t pass the content Offset value of A to B here to scroll them together as they loads at different points due to content requirement.I need the exact x points displaced while scrolling in A, then may be pass it to B.
I have also tried getting the velocity from pangesture of A and passing it to B, which doesn’t work smoothly.
How can I achieve a smooth scrolling for both views ?
Upvotes: 0
Views: 267
Reputation: 7510
It's not entirely clear what you're trying to do. But if you want to be updated about when scroll view A changes it's contentOffset
you can subclass UIScrollView
and pass the data through a delegate or a closure.
class ScrollView: UIScrollView {
var contentOffsetChanged: ((CGPoint)->())?
override var contentOffset: CGPoint {
didSet {
if let contentOffsetChanged = contentOffsetChanged {
contentOffsetChanged(contentOffset)
}
}
}
}
Update
After reading the comment you left me and the one you wrote to iOS Geek, it seems contradictory. There are a few possibilities for how your math would work out so don't take my exact solution as the answer, but more of the design. I think this is the design you're interested in.
class Controller: UIViewController, UIScrollViewDelegate {
let scrollView = UIScrollView()
var scrollViewB: UIScrollView?
var initialOffset: CGPoint = .zero
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
}
func loadScrollViewB() {
initialOffset = scrollView.contentOffset
scrollViewB = UIScrollView()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self.scrollView {
var contentOffset: CGPoint = .zero
contentOffset.x = initialOffset.x - scrollView.contentOffset.x
scrollViewB?.contentOffset = contentOffset
}
}
}
Upvotes: 1