我有一个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];
}
如何在用户更改后立即更改显示的单位? 谢谢!
答案 0 :(得分:2)
将viewWillAppear:
内的代码移动到单独的方法中。当用户更改设置时调用该方法。
答案 1 :(得分: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
}