CGFloat 最小值与当前值

CGFloat MinimumValue vs CurrentValue

我用 uiview 创建了一个自定义滑块 class ...一切正常,但我遇到了问题...

在我的视图控制器中以这种方式实现自定义滑块class

主要ViewController

#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 但我无法获取它 运行 你能帮我解决这个问题吗?

自定义滑块 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
    }
}

您的代码目前只检查滑块何时初始化,但如果稍后设置 currentValue 则不检查。

一般来说,如果我在实例变量的 setter/getter 中,我更喜欢直接访问该实例变量以避免混淆和可能的无限递归,但是您编写的代码没问题。