Reputation: 43
I want to track the position of my horizontal scrollView, yet when I print the contentOffset.x or contentOffset, they always return zero. This is the code for my class:
import UIKit
class ScrollForecast: UIScrollView, UIScrollViewDelegate {
@IBOutlet weak var scrollTemp: UILabel!
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print(self.contentOffset.x)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
scrollView.decelerationRate = UIScrollViewDecelerationRateFast
let cellWidth: CGFloat = 40
var index = round(targetContentOffset.pointee.x / cellWidth)
targetContentOffset.pointee.x = index * cellWidth
}
}
Any ideas as to what might be the problem? The code inside scrollViewDidEndDragging works just fine and sets the contentOffset so that the scrollView snaps every 40 points.
Upvotes: 2
Views: 1443
Reputation: 2730
Make sure that scrollView.contentSize
is large enough to allow it to scroll. Otherwise targetContentOffset.pointee.x
will be zero.
Upvotes: 1