UISlider 可捕捉到固定的步数(如 iOS 7 设置应用中的文本大小)
我正在尝试创建一个 UISlider
,让您可以从数字数组中进行选择。每个滑块位置应等距,并且滑块应卡入每个位置,而不是在它们之间平滑滑动。 (这是 iOS 7 中引入的 Settings
> General
> Text Size
中滑块的行为。)
我想要选择的数字是:-3, 0, 2, 4, 7, 10 , 和12.
(我对 Objective-C 很陌生,所以完整的代码示例比代码片段更有帮助。=)
I'm trying to create a UISlider
that lets you choose from an array of numbers. Each slider position should be equidistant and the slider should snap to each position, rather than smoothly slide between them. (This is the behavior of the slider in Settings
> General
> Text Size
, which was introduced in iOS 7.)
The numbers I want to choose from are: -3, 0, 2, 4, 7, 10, and 12.
(I'm very new to Objective-C, so a complete code example would be much more helpful than a code snippet. =)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果有人还需要捕捉动画,则可以执行以下操作:
您可以从 swift
slider.isContinously = false
执行相同操作,ViewController
中添加以下@IBAction
:受到这个答案的启发
If anyone also needs snaping animation then can do the following:
You can do the same from swift
slider.isContinuous = false
@IBAction
in yourViewController
:I was inspired by this answer
与 PengOne 类似的方法,但我进行了手动舍入以使其更清楚发生了什么。
Similar approach as PengOne, but I did manual rounding to make it more clear what was happening.
其他一些答案有效,但这将为您在滑块中的每个位置之间提供相同的固定空间。在此示例中,您将滑块位置视为包含您感兴趣的实际数值的数组的索引。
编辑:这是 Swift 4 中的一个版本,它使用回调对 UISlider 进行子类化。
Some of the other answers work, but this will give you the same fixed space between every position in your slider. In this example you treat the slider positions as indexes to an array which contains the actual numeric values you are interested in.
Edit: Here's a version in Swift 4 that subclasses UISlider with callbacks.
如果步骤之间有规则的空格,则可以像这样使用
15
值:If you have regular spaces between steps, you can use it like this for
15
value:这适用于我的特殊情况,使用@IBDesignable:
需要偶数整数间隔:
This worked for my particular case, using @IBDesignable:
Requires even, integer intervals:
答案基本上与这个答案相同UISlider增量为 5
要修改它以适合您的情况,您需要创建一个仅返回您想要的值的舍入函数。例如,您可以做一些简单的事情(虽然很hacky),如下所示:
现在使用上一篇文章中的答案来舍入该值。
最后,实施更改:
The answer is essentially the same at this answer to UISlider with increments of 5
To modify it to work for your case, you'll need to create a rounding function that returns only the values you want. For example, you could do something simple (though hacky) like this:
Now use the answer from the previous post to round the value.
Finally, implement the changes: