在Objective-C中输出多个滑块的平均值

时间:2014-07-10 15:07:47

标签: objective-c xcode xcode5

我是Objective-C的初学者,我想知道如何将来自多个滑块的值数据的平均值输出到标签。

我走了这么远:

的.h

@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UISlider *Slider;
- (IBAction)updateValue:(UISlider *)sender;
@property (weak, nonatomic) IBOutlet UILabel *persentage;

@property (weak, nonatomic) IBOutlet UISlider *Slider2;
- (IBAction)updateValue2:(UISlider *)sender;
@property (weak, nonatomic) IBOutlet UILabel *persentage2;

@property (weak, nonatomic) IBOutlet UILabel *averagePercentage;


@end

的.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (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.
}

- (IBAction)updateValue:(UISlider *)sender {
    _percentage.text = [NSString stringWithFormat:@"%.2f %%",sender.value*100];
}
- (IBAction)updateValue2:(UISlider *)sender {
    _percentage2.text = [NSString stringWithFormat:@"%.2f %%",sender.value*100];
}

@end

我想要做的是,我想让“averagePercentage”标签显示两个输入的平均百分比。我该怎么办?我也在使用故事板。

1 个答案:

答案 0 :(得分:0)

向视图控制器添加一个方法,并从您的IBActions调用它:

@interface ViewController ()
- (void)updateAveragePercentage;
- (NSString *)stringForPercentage:(float)value;
@end

@implementation ViewController
...

- (IBAction)updateValue:(UISlider *)sender {
    self.percentage.text = [self stringForPercentage:sender.value];
    [self updateAveragePercentage];
}
- (IBAction)updateValue2:(UISlider *)sender {
    self.percentage2.text = [self stringForPercentage:sender.value];
    [self updateAveragePercentage];
}

- (void)updateAveragePercentage
{
    float average = 0.5f * (self.Slider.value + self.Slider2.value);
    self.averagePercentage.text = [self stringForPercentage:average];
}

- (NSString *)stringForPercentage:(float)value
{
    return [NSString stringWithFormat:@"%.2f %%", value * 100];
}

@end

请注意,我在.m文件的类扩展声明中声明了updateAveragePercentage,因为没有必要让它公开显示。

我还添加了stringForPercentage方法,以便stringWithFormat代码不会重复。您可能需要考虑使用NSNumberFormatter而不是stringWithFormat来更好地控制和定位数字格式。