0

我有一个 UISegmentedControl 来处理温度单位 (ºC/ºF) 的设置。
它可以正常工作,但如果用户更改设置,除非用户导航到另一个视图控制器然后返回到有问题的视图控制器,否则显示的单元不会更改(刷新自身)。

我正在使用

- (void)viewWillAppear:(BOOL)animated
{
//Gets user setting choice for Fahrenheit or Celsius
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
temperatureSetting = [[preferences valueForKey:@"temperature setting"]intValue];
//For getting the current value of temperature from the JSON data
NSInteger temp = [[conditions objectForKey:@"temperature"]intValue];
//For checking the user's setting to display either Fahrenheit or Celsius
if (temperatureSetting == 0) {
    temp = (temp * 1.8) + 32;
    temperatureLabel.text = [NSString stringWithFormat:@"%i°F", temp];
} else {
    temperatureLabel.text = [NSString stringWithFormat: @"%iºC", temp];
}
}


- (IBAction)temperatureSelection:(UISegmentedControl *)sender {
//Used to save settings
NSUserDefaults *temperaturePreference = [NSUserDefaults standardUserDefaults];
//To check which segment is selected and save the value but also remember it
if ([sender selectedSegmentIndex] == 0) {
    [temperaturePreference setInteger:0 forKey:@"temperature setting"];
    [selectedSegment setInteger:0 forKey:@"segment setting"];
} else if ([sender selectedSegmentIndex] == 1) {
    [temperaturePreference setInteger:1 forKey:@"temperature setting"];
    [selectedSegment setInteger:1 forKey:@"segment setting"];
}
//To make sure the setting is saved
[temperaturePreference synchronize];
[selectedSegment synchronize];

}

如何在用户更改后立即更改显示单位?
谢谢你!

4

2 回答 2

2

将里面的代码viewWillAppear:移到一个单独的方法中。当用户更改设置时调用该方法。

于 2012-09-16T11:31:28.090 回答
1

尝试在方法结束之前添加该行代码- (IBAction)temperatureSelection:(UISegmentedControl *)sender

- (IBAction)temperatureSelection:(UISegmentedControl *)sender{
//..etc
temperatureSetting = [[temperaturePreferences valueForKey:@"temperature setting"]intValue];
if (temperatureSetting == 0) {
 temp = (temp * 1.8) + 32;
 temperatureLabel.text = [NSString stringWithFormat:@"%i°F", temp];
} else {
 temperatureLabel.text = [NSString stringWithFormat: @"%iºC", temp];
}
 [self.view setNeedsDisplayInRect:temperatureLabel.frame];//probably is not needed it forces the view to redraw itself as it mark as dirty
}
于 2012-09-16T11:39:50.493 回答