Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A bug of UIScrollView contentOffset?

I set the property isPagingEnabled of a scrollView to true, like this:

let scrollView = UIScrollView(frame: view.bounds)
scrollView.contentSize = CGSize(width: view.bounds.width * 2, height: 0)
scrollView.delegate = self
scrollView.isPagingEnabled = true
view.addSubview(scrollView)

and delegate method:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    print(scrollView.contentOffset.x)
}

When scrolling the view to the boundary, the console print, as shown in:

enter image description here

and

enter image description here

The values in the red box should not be printed out, right?

But, if setting isPagingEnabled to false, the console print is normal. Is this a bug of UIScrollView?

like image 794
Mokyz Avatar asked Jun 03 '26 20:06

Mokyz


2 Answers

Your Content offset is showing wrong because your are using content size in viewdidload use content size in this method than print your content off set

 override func viewDidLayoutSubviews()
 {
  scrollView.contentSize = CGSize(width: view.bounds.width * 2, height: 0)
 }
like image 134
Lalit kumar Avatar answered Jun 06 '26 10:06

Lalit kumar


As far as i Know, Its working correctly, when you are setting contentSize to your scrollview, that will respond to their delegate at first time itself.

func scrollViewDidScroll(_ scrollView: UIScrollView)

Whenever user try to scroll or drag, the above delegate will call recursively, Here your contentSize of width is double of Your view bounds width(so there is two page, the contentOffset.x will start with 0 and current position of scroll, if it is in second page, that will give your view width * n ), and you set isPagingEnabled to true.

Check this https://developer.apple.com/reference/uikit/uiscrollview/1619404-contentoffset

The default value is CGPoint​Zero.

Actually contentOffset will tell you that current scroll position.

like image 33
karthikeyan Avatar answered Jun 06 '26 09:06

karthikeyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!