0

我正在使用 aNSStepper和 a NSTextField。用户可以使用文本字段设置值,也可以使用 NSStepper 更改值。我将使用下面的示例引用我的问题:
假设我的步进器的当前值为 4,步进器的增量值为 2: 在此处输入图像描述

在我单击 NSStepper 上的向上箭头后,值变为:
在此处输入图像描述

现在假设当前值为 4.5,即:
在此处输入图像描述

使用向上箭头后,值变为:
在此处输入图像描述

我需要的是,当当前值为 4.5 时,使用向上箭头后,值变为6而不是 6.5

非常感谢任何实现这一目标的想法!

4

2 回答 2

1

我需要的是,当当前值为 4.5 时,使用向上箭头后,值变为 6 而不是 6.5

很难确切地说出您在问什么,但要猜测一下:听起来您想删除数字的小数部分并按您定义的步长增加 (2)。您可以通过该floor()功能执行此操作。有关其他 Objective-C 数学函数的信息,请参见此处

double floor ( double ) - 删除参数的小数部分

NSLog(@"res: %.f", floor(3.000000000001)); 
//result 3 
NSLog(@"res:%.f", floor(3.9999999));
//result 3
于 2012-07-18T16:33:26.683 回答
0

如果我理解您想要什么,此代码将为您提供下一个偶数(向上或向下取决于您单击的箭头),但仍允许您在文本字段中输入非整数数字。tf 和 stepper 是 IBOutlets 并且 num 是一个属性(浮点数),它在单击箭头之前跟踪步进器的值,以便您可以与新数字进行比较以查看是否单击了向上或向下箭头。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.num = 0;
    self.tf.intValue = 0; //the stepper is set to 0 in IB
}


-(IBAction)textFieldDidChange:(id)sender {
    self.num = self.stepper.floatValue = [sender floatValue];
}


-(IBAction)stepperDidChange:(id)sender {
    if (self.num < self.stepper.floatValue) { //determines whether the up or down arrow was clicked
        self.num = self.stepper.intValue = self.tf.intValue = [self nextLargerEven:self.num];
    }else{
        self.num = self.stepper.intValue = self.tf.intValue =[self nextSmallerEven:self.num];
    }
}

-(int)nextLargerEven:(float) previousValue {
    if ((int)previousValue % 2 == 0) {
        return (int)previousValue + 2;
    }else
        return (int)previousValue + 1;
}


-(int)nextSmallerEven:(float) previousValue {
    if ((int)previousValue % 2 == 0) {
        if ((int)previousValue == previousValue) {
            return (int)previousValue - 2;
        }else{
            return (int)previousValue;
        }
    }else
        return (int)previousValue - 1; 
}
于 2012-07-18T16:19:47.860 回答