How can I use a UIScrollView to change values, just like a UISlider?

馋奶兔 提交于 2019-12-07 00:39:36

I have to admit to not being 100% sure how you're using a scrollview as a slider, but you can use the contentOffset property to get "The point at which the origin of the content view is offset from the origin of the scroll view."

You'll need to do some maths to turn that into the value you want, but it's simple stuff. Suppose your scroll view is horizontal and has can be scrolled up to 400px across. That is, if contentOffset is 0 then you're at the start and if contentOffset is 400px then you're at the end. How you've used the scrollview will dictate exactly how you work this out, if you're desperate then you can just print the value of contentOffset programmatically and observe the range empirically.

In that case, you can get the proportion of the distance across the scrollview you are at by something like:

CGFloat proportionOffset = scrollView.contentOffset/400.0f;

If you then want to model the range [startX, endX] then just work out:

CGFloat offset = startX + proportionOffset * (endX - startX);

proportionOffset ends up in the range 0 to 1, at 0 when contentOffset is 0 and at 1 when contentOffset is 400. If, say, startX is 15 and endX is 35 then endX - startX is 20. If you multiply a number in the range 0 to 1 by 20 then you get a number in the range 0 to 20. That's how far through your range you want to be. But your range doesn't necessarily start at 0, so you need to add on the value of startX.

For efficiency terms, it's smart to set yourself up as a delegate of the scrollview and check the new contentOffset only when you receive a scrollViewDidScroll:. Otherwise you're doing a lot of polling that simply isn't necessary and, at the absolute worst, severely impeding the CPU's ability to sleep (and hence reduce heat and save battery).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!