【问题标题】:CGFloat MinimumValue vs CurrentValueCGFloat MinimumValue 与 CurrentValue
【发布时间】:2018-04-03 03:45:27
【问题描述】:

我创建了一个带有 uiview 类的自定义滑块......一切正常,但我只是遇到了一个问题......

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

主视图控制器

#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;
}

【问题讨论】:

  • @beyowulf 在约束和 addSubview 中?
  • @beyowulf 好的,非常感谢,这也适用于 uilabel、uiview 等... ???你能告诉我一些关于我的问题吗?
  • @beyowulf 告诉我你认为 self.stats 和 _stats 之间的最佳选择
  • 是的,我会在 getter 和 setter 中使用 _stats。 self.stats 其他任何地方。这是所有 obj-c 属性的好习惯。
  • @beyowulf 你为什么删除你的 cmets?

标签: ios uiview uiviewcontroller cgfloat


【解决方案1】:

好像你想要的

if (self.currentValue <= self.minimumValue) {
    self.currentValue = self.minimumValue;
}

在currentValue 的设置器中。例如:

- (void)setCurrentValue:(CGFloat)currentValue {
    _currentValue = currentValue;
    if (_currentValue < self.minimumValue) {
        _currentValue = self.minimumValue;
    }
    if (_currentValue > self.maximumValue) {
        _currentValue = self.maximumValue
    }
}

您的代码目前仅检查滑块何时初始化,但不检查currentValue 是否稍后设置。

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

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2014-04-20
    相关资源
    最近更新 更多