【问题标题】:UISwitch/UISlider values when switching ViewControllers切换 ViewController 时的 UISwitch/UISlider 值
【发布时间】:2017-04-19 08:10:37
【问题描述】:

您将如何保留 UISwitch 或 UISlider 的值,以便当您离开并返回 ViewController 时,它的值与您离开时的值相同?

我对swift没有太多的知识或经验,所以如果可以的话,请用Objective-C解释一下!

【问题讨论】:

  • 这取决于,您退出应用程序时是否必须保留该值?
  • 不,仅适用于应用程序运行时 - 应用程序关闭后可以重置。
  • 您需要将UISlider 的值保存在某处。 NSUserDefault 可以成为候选人。

标签: ios objective-c xcode


【解决方案1】:

您可以像这样将开关状态保存到 NSUserDefault。

添加与您的开关按钮相关的操作

.h 文件

- (IBAction)changeStatus:(id)sender;

.m 文件

- (IBAction)changeStatus:(id)sender {
Boolean status;
UISwitch *mySwitch = (UISwitch *)sender;
if ([mySwitch isOn]) {
    status = 1;
} else {
    status = 0;
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:status forKey:@"switchStatus"];
[defaults synchronize];

}

并加载使用

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
Boolean switchStatus = [defaults boolForKey:@"switchStatus"];
if (switchStatus)
{
    [_switchButton setOn:YES animated:YES];
}else{
    [_switchButton setOn:NO animated:YES];
}

【讨论】:

    【解决方案2】:

    您可以将值保存在模型中,或者 - 为了方便您 - 在您的 AppDelegate 中您在前一个问题中建立了连接。注意:您应该了解 MVC - 这只是为了让您轻松。 MVC 的一个很好的起点是这个答案:Design Pattern - Objective-C - MVC Model View Controller

    扩展你的 appDelegate.h
    @property double sliderValue;
    

    然后在你的 viewController.m 中实现

    - (void)viewDidDissapear {
        MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate setSliderValue:YourSlider.value];
    }
    

    下次执行时加载它

    - (void)viewWillAppear {
        MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
        [yourSlider setValue:appDelegate.sliderValue];
    }
    

    不要忘记在 viewCONtroller.m 文件中导入 AppDelegate.h 文件。

    #import "MyAppDelegate.h"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多