我创建了一个带有 uiview 类的自定义 slider ...一切正常,但我遇到了问题...
在我的 View Controller 中以这种方式实现自定义 slider 类
主视图 Controller
#pragma mark SMALL STATS
-(KPStatsSlider *)statsSlider {
if (!_statsSlider) {
_statsSlider = [[KPStatsSlider alloc] init];
_statsSlider.minimumValue = 18;
_statsSlider.maximumValue = 30;
_statsSlider.currentValue = 12;
_statsSlider.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:self.statsSlider];
[self.statsSlider.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:115].active = YES;
[self.statsSlider.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:0].active = YES;
[self.statsSlider.heightAnchor constraintEqualToConstant:70].active = YES;
[self.statsSlider.leftAnchor constraintEqualToAnchor:self.view.centerXAnchor constant:0].active = YES;
}
return _statsSlider;
}
如你所见,我可以赋值: 当前/ 最低限度/ 最大
在我的个性化 UIView 中,我实现了此功能以防止 CurrentValue 值小于 MinimumValue 但我无法让它运行,你能帮我解决这个问题吗?
自定义 slider UIView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
[self defaultValue];
[self setupStatsTitle];
[self trackLine];
if (self.currentValue <= self.minimumValue) {
self.currentValue = self.minimumValue;
}
}
return self;
}
最佳答案
看来你想要
if (self.currentValue <= self.minimumValue) {
self.currentValue = self.minimumValue;
}
在 currentValue
的 setter 中。例如:
- (void)setCurrentValue:(CGFloat)currentValue {
_currentValue = currentValue;
if (_currentValue < self.minimumValue) {
_currentValue = self.minimumValue;
}
if (_currentValue > self.maximumValue) {
_currentValue = self.maximumValue
}
}
您的代码当前仅检查 slider 何时初始化,而不检查是否稍后设置 currentValue
。
一般来说,如果我在实例变量的 setter/getter 中,我更喜欢直接访问实例变量,以避免混淆和可能的无限递归,但是您编写的代码是可以的。
关于ios - CGFloat 最小值与当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46875043/