English 中文(简体)
如何将用户设置值保留到 UISwitch?
原标题:How to keep user set values to UISwitch?

我从接口构建器中提取了 UISwitch。 那一次它就是状态 。 运行程序之后, 当我将其位置更改为 FOF, 然后转到其他屏幕, 然后又返回到屏幕上, 切换 sates 显示在不是我之前设置的 FOF 上 。 任何人都可以告诉我如何显示 UISwitch 位置或状态 。 现在它总是显示在什么时候我来到这个开关屏幕上 。 请帮助我。 提前感谢 。

最佳回答

当您更改值时, 将其保存到 NNSUser Default, 所以当您再次回到屏幕时, 您会查看首选项值并将其设置为开关

- (void)saveValue  {
    NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
    [preferences setBool:value forKey:@"switchOnOff"];
    [preferences synchronize];
}

- (BOOL)readValue  {
    NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
    return [preferences boolForKey:@"switchOnOff"];
}
问题回答

给UISwitch一个出口

@property (retain, nonatomic) IBOutlet UISwitch *sswitch;

使连接。

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if( [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"] )
    {
        [sswitch setOn:YES]
    }
    else
    {
        [sswitch setOn:NO]
    }
}

当切换状态被更改时, 请在 NSUser Defaults 中保存值

当您更改开关状态时, 请在 NNSUser Defaults 中存储整数值, 并查看您开关所在的视图控制器的 DidAppear 方法 。 只要通过从 NSSUser Defaults 中获取数值来设置开关状态

//store value to nsuserdefaulrs
    [[NSUserDefaults standardUserDefaults] setBool:switch.on forKey:@"switchStatus"];

//get value from nsuserdefaulrs

[switch setOn:[[NSUserDefaults standardUserDefaults] boolForKey:@"switchStatus"]];

You have to save values in
1. Model class
2. NSUserDefaults
3. Plist
4. Document file.

最好的方式是模型类。您将很容易得到代码 用于这些在Staackoverflow中。

如果它是您在 IB 中添加的开关, 您可以在此设置初始状态 。 否则, 在您将开关与 IB 输出器连接后, 您可以在您的视图中添加类似 :

[保存纸套设于:NO];

它会将开关设置为关闭状态。 您需要确保开关与 IBoutlet 变量链接 。





相关问题
List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...

iPhone NSUserDefaults persistance difficulty

In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...

Writing a masked image to disk as a PNG file

Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...

Resize UIImage with aspect ratio?

I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...

Allowing interaction with a UIView under another UIView

Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...

热门标签