有什么方法可以为 UISlider 设置刻度线。NSSlider 有一个叫做
- (void)setNumberOfTickMarks:(NSInteger)numberOfTickMarks
. 但 UISlider 似乎没有。
我想要做的是将滑块值设置为 0,1,2,3,4 等,如果说我将最小值设置为 0,最大值设置为 5。现在 UISLider 返回类似 0.0,0.1,0.2,0.3 等 4.8 ,4.9,5.0 基于我上面给出的例子。
有什么帮助吗??
UISlider
没有任何标记。
要获得您指定的行为,您必须将滑块返回的数字四舍五入到最接近的整数。
因此,当您开始滑动时,滑块报告的值为 0.1 或 0.2,将其四舍五入为 0。直到它达到 0.5,然后四舍五入为 1。
然后当滑块停止滑动时,您可以将其值设置为四舍五入的数字,这将使滑块“捕捉”到该位置,就像捕捉到刻度线一样。
如果您想要视觉标记,则必须自己实现。
是的,我认为子类化是要走的路。这就是我所做的:
TickSlider.h…</p>
/**
* A custom slider that allows the user to specify the number of tick marks.
* It behaves just like the NSSlider with tick marks for a MacOS app.
**/
@interface TickSlider : UISlider
/**
* The number of tickmarks for the slider. No graphics will be draw in this
* sublcass but the value of the slider will be rounded to the nearest tick
* mark in the same way/behaviour as the NSSlider on a MacOS app.
* @discussion This value can be set as a UserDefinedAttribute in the xib file.
**/
@property (nonatomic) NSInteger numberOfTickMarks;
@end
TickSlider.m…</p>
#import "TickSlider.h"
@implementation TickSlider
- (void)setValue:(float)value animated:(BOOL)animated {
float updatedValue = value;
if (self.numberOfTickMarks > 0) {
updatedValue = MAX(self.minimumValue, MIN(value, self.maximumValue));
if (self.numberOfTickMarks == 1) {
updatedValue = (self.minimumValue + self.maximumValue) * 0.5f;
}
else {
const int kNumberOfDivisions = (self.numberOfTickMarks - 1);
const float kSliderRange = ([self maximumValue] - [self minimumValue]);
const float kRangePerDivision = (kSliderRange / kNumberOfDivisions);
const float currentTickMark = roundf(value / kRangePerDivision);
updatedValue = (currentTickMark * kRangePerDivision);
}
}
[super setValue:updatedValue animated:animated];
}
@end
如上所述,转换为 int 使滑块的行为就像您在拇指旁边滑动一样。上面的代码很有趣,它允许您指定更多的“停止值”(ticks)作为最大值设置。
如果您需要一个简单的“整数滑块”,则舍入(值 + 0.25)实际上会使滑块表现得非常好。这是我使用的代码:
@interface IntegerSlider : UISlider
@end
@implementation IntegerSlider
- (void) setValue: (float) value
animated: (BOOL) animated
{
value = roundf(value + 0.25);
[super setValue: value
animated: animated];
}
@结尾
我只是强制[slider value]
转换为 int 来实现这一点。