0

我正在尝试编写自己的间歇训练计时器。现在我在读取 UIStepper 控件的值时遇到问题。

我在 UIStepper 控制器上设置了一个 int ,它到目前为止有效。

- (IBAction)stepperChange:(id)sender {

// converting double to int
int temp = [[NSNumber numberWithDouble:[(UIStepper *)sender value]] intValue];

NSLog(@"stepper was pressed. Current values is %d", [[NSNumber numberWithDouble:[(UIStepper *)sender value]] intValue]);

self.intervalSeconds.text = [NSString stringWithFormat:@"%i", [[NSNumber numberWithDouble:[(UIStepper *)sender value]] intValue]];

mainInt = [[NSNumber numberWithDouble:[(UIStepper *)sender value]] intValue];

}

到目前为止,一切都很好。问题是,我想在定时器达到 0 时将其重置为 UISteppers 值。但是当我尝试在没有 (id)sender 的情况下直接读取步进器值时,我总是得到 0 的值。

例如

-(void)readStepperValue {

NSLog(@"Read UIStepper control value: %f", [intervalStepper value]);

}

我想这只是一个愚蠢的初学者错误......


好的,我刚刚做了一个超级简单的测试应用程序,代码如下所示:

vierController.h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {

IBOutlet UIStepper *stepper;
IBOutlet UILabel *stepperValue;
}

@property (nonatomic, strong) UIStepper *stepper;
@property (nonatomic, strong) UILabel *stepperValue;

- (IBAction)showStepperValue;

@end

视图控制器.m:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize stepper, stepperValue;

- (IBAction)showStepperValue {
int temp = stepper.value;
stepperValue.text = [NSString stringWithFormat:@"%i", temp];
[self showValue];
}


- (void)showValue {
int temp = stepper.value;
NSLog(@"stepper.value: %i", temp);
}


- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

标签从 IBAction 方法中正确更新。但是,当我调用不在 IBAction 内的单独方法 (showValue) 时,它无法读取控制器的值....

4

1 回答 1

0

试试这种方式。

视图控制器.h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, strong) IBOutlet UIStepper *stepper;
@property (nonatomic, strong) IBOutlet UILabel *stepperValue;

- (IBAction)showStepperValue;

@end

视图控制器.m:

#import "ViewController.h"

@implementation ViewController

- (IBAction)showStepperValue {
    double temp = self.stepper.value;
    self.stepperValue.text = [NSString stringWithFormat:@"%f", temp];
    [self showValue];
}

- (void)showValue {
    double temp = self.stepper.value;
    NSLog(@"self.stepper.value: %f", temp);
}

@end

摆脱 iVar 并仅依赖属性不仅减少了您需要编写的代码量,而且还有助于消除任何 iVar/属性绑定错误。

更新: self.stepper.value 是 double 而不是 int (但这不是你的问题)。

于 2013-03-31T13:39:27.997 回答