I have a UIButton
- (IBAction)checkButton:(id)sender {
if (!checked) {
[checkBoxButton setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
checked = YES;
} else if (checked) {
[checkBoxButton setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
checked = NO;
}
}
I want to save the user input, weather the button is checked or not, even after the app closes. Help me with codes anyone? I don't know the codes to use NSUserDefaults for saving BOOL state.
Use it by below way:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool: checked forKey:#"Status"];
[defaults synchronize];
To retrieve it,
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL state = [defaults boolForKey:#"Status"];
Set images for both Normal and selected state of a button as
[checkBoxButton setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateSelected];
[checkBoxButton setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
and in IBAction set
- (IBAction)checkButton:(id)sender {
if (!checked) {
[checkBoxButton setSelected:NO];
checked = YES;
} else if (checked) {
[checkBoxButton setSelected:YES];
checked = NO;
}
}
Here is an Example:
if ([[NSUserDefaults standardUserDefaults] boolForKey:hasLaunchedOnceKey])
{
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:hasLaunchedOnceKey];
[[NSUserDefaults standardUserDefaults] synchronize]; //Saves the data
}
Where I have:
static NSString *hasLaunchedOnceKey = #"HasLaunchedOnce";
Declared before the #implementation statement.
See this for an extensive tutorial.
**Note: You do not need to declare anything in any sort of plist files afaik. You can simply check for and set these keys and they will be dynamically created if they don't exist. Works that way for me anyways.
Happy programming!
My way is too easy .. You don't need to take any other variable. On initialise set your button tag ZERO and after use this.
- (IBAction)checkButton : (id)sender {
if ([sender tag] == 0) {
[sender setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
[sender setTag:1];
} else {
[sender setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
[sender setTag:0];
}
}
Thanks & Cheers .. May be helpfull..
Related
I'm very new to iOS development. I've currently got an app with some SFX in there. I've found a couple of other threads which explain the approach / logic, which I full understand, but it's the code I'm after as I have no idea of the syntax.
If I were to use a UI Switch, how would I turn off any SFX that's used within the app?
Any help and assistance would be greatly appreciated.
Thank you all.
How are you using your sfx? If you could upload your code it would help. But you can try this?
- (IBAction)SwitchValueChanged:(id)sender
{
if([sender isOn])
{
NSLog(#"Switch is ON");
//On Your SFX
}
else
{
NSLog(#"Switch is OFF");
//Off Your SFX
}
}
I don't really understand what you mean by Some SFX So its hard to provide help
There might be an option for you. So in the
.h file where the switch to turn it off, put this code.
#interface SettingScreen : UIViewController<AVAudioPlayerDelegate,AVAudioSessionDelegate>
{
AVAudioPlayer *audioplayer;
}
in .m file
-(void)viewDidLoad
{
NSString* BS_path_blue=[[NSBundle mainBundle]pathForResource:#"Click" ofType:#"mp3"];
audioplayer =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue] error:NULL];
audioplayer.delegate=self;
[audioplayer prepareToPlay];
UISwitch *soundsButton = [[UISwitch alloc]initWithFrame:CGRectMake(180, 8, 130, 27)];
[self.view addSubview:soundsOnOffButton];
[soundsOnOffButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
soundsButton.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"sound"];
}
-(void)buttonAction:(UIButton *)sender
{
if (soundsButton.on)
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"sound"];
[[NSUserDefaults standardUserDefaults] synchronize];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"sound"]==YES)
{
[audioplayer play];
}
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"sound"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
Now if you want to play a sound for something. (Button used as example) in another screen , add delegate and first four lines to your file then add this line to their action.
-(void)buttonAction:(UIButton *)sender
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"sound"]==YES)
{
[audioplayer play];
}
// other code
}
Hope it works.
I have a two buttons. One that shows when the sound is playing and one when the sound isn't playing. However, when I switch it off and switch view controllers. And i come back to the main menu view controller the sound is back on. I want to keep the sound on or off based on the user setting.
(IBAction)pauseSound
{
BOOL shouldPlaySound = YES;
[[NSUserDefaults standardUserDefaults] setBool:shouldPlaySound forKey:#"shouldPlaySound"];
if (![sound isPlaying]) {
[sound play];
[soundButton setBackgroundImage:[UIImage imageNamed:#"SoundOn.png"] forState:UIControlStateNormal];
}else {
[sound pause];
[soundButton setBackgroundImage:[UIImage imageNamed:#"SoundOff.png"] forState:UIControlStateNormal];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
A good way to do this is saving wether or not to play the Sound in the NSUserDefaults, so the setting is remembered by your app. Set it i.e. via
BOOL shouldMuteSound = ...//set it corresponding to your button presses/visibility
[[NSUserDefaults standardUserDefaults] setBool:shouldMuteSound forKey:#"shouldMuteSound"];
//call this to immediatly update the userDefaults
[[NSUserDefaults standardUserDefaults] synchronize];
And load it via
BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:#"shouldMuteSound"];
I didn't get it at first that the buttons are inside the same viewController that plays the sound. That code should help you:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:#"shouldMuteSound"];
if(!shouldMuteSound){
[self playSound];
}else{
[self stopSound];
}
}
- (void)playSound{
if(!sound){
NSString *path = [[NSBundle mainBundle] pathForResource:#"Main Menu" ofType:#"mp3"];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
sound.numberOfLoops = -1;
}
if (![sound isPlaying]){
[sound play];
}
[soundButton setBackgroundImage:[UIImage imageNamed:#"SoundOn.png"] forState:UIControlStateNormal];
}
- (void)stopSound{
[sound pause];
[soundButton setBackgroundImage:[UIImage imageNamed:#"SoundOff.png"] forState:UIControlStateNormal];
}
- (IBAction)soundButtonTapped{
BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:#"shouldMuteSound"];
shouldMuteSound = !shouldMuteSound;
[[NSUserDefaults standardUserDefaults] setBool:shouldMuteSound forKey:#"shouldMuteSound"];
[[NSUserDefaults standardUserDefaults] synchronize];
if(shouldMuteSound){
[self stopSound];
}else{
[self playSound];
}
}
As many others here I am new to Xcode and would like to ask a basic question. When checking a box and leaving Xcode, this value is not saved (unchecked box) when I reopen the Xcode project.
I have seen different discussions here: e.g. how to save a checkbox value check/uncheck to NSUserDefaults but it is not working in my code. Do you have a hint where the problem is?
In my .h I have created an instance of a BOOL (called “checked“) and a UIButton is connected both as an IBAction and as an IBOutlet.
- (void)viewDidLoad{
checked = NO;
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"Negative"];
BOOL checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
[[NSUserDefaults standardUserDefaults] synchronize];
[super viewDidLoad];
NSUserDefaults *defaults70 = [NSUserDefaults standardUserDefaults];
checked = [defaults70 boolForKey: #"boxIsChecked70"];
[self checkTheBox];
[self updateLabels];}
- (IBAction)CheckCOUTCheckButton:(id)sender {
NSUserDefaults *defaults70 = [NSUserDefaults standardUserDefaults];
if (! checked) {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxcheckedimage.png"] forState:UIControlStateNormal];
checked = YES;
[defaults70 setBool:checked forKey:#"boxIsChecked70"];}
else if (checked) {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxuncheckedimage.png"] forState:UIControlStateNormal];
checked = NO;
[defaults70 setBool:checked forKey:#"boxIsChecked70"];}
[defaults70 synchronize];}
- (void) checkTheBox {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (! checked) {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxuncheckedimage.png"] forState:UIControlStateNormal];
}
else if (checked) {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxcheckedimage.png"] forState:UIControlStateNormal];
}
- (IBAction)ClearAllFields:(id)sender {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxuncheckedimage.png"] forState:UIControlStateNormal];
checked = NO;}
Your problem is an problem of scope. You are defining a second variable called checked and confusing which one you're setting.
- (void)viewDidLoad{
checked = NO;
in this line you are setting the property - ie the self.checked value to NO.
BOOL checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
[[NSUserDefaults standardUserDefaults] synchronize];
in this line however you are declaring a NEW local variable that will only exist within viewDidLoad.
try removing the BOOL before it. When viewDidLoad returns this local variable will go out of scope and disappear.
checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
[[NSUserDefaults standardUserDefaults] synchronize];
so later on when you set the checkbox as part of checkTheBox you're reading the property, not your local variable that you set.
let me know if this isn't clear.
I am not sure if this is your only problem, but in your viewDidLoad, you are basically setting a value before you're reading it:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"Negative"];
BOOL checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
You probably want to do this:
BOOL checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
I have 4 ui switches on one view controller and two are working perfect however the last two have setup so you can only click on either group or two player however when you click on two player on then click save and go back in it turns both switches on however if you do the same in group it dosnt not do this?
Anyone see what im doing wrong here?
-(void)stateSwitched:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? #"YES" : #"NO" forKey:#"truthonoff"];
[defaults synchronize];
}
-(void)stateSwitcheddare:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool: tswitch.isOn forKey:#"groupswitch"];
[defaults setBool: tswitch.isOn forKey:#"twoplayerswitch"];
[defaults synchronize];
}
-(void)stateSwitchedtwoplayer:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
//turns two player off when on and soforth
self.groupswitch.on =! tswitch.isOn;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool: tswitch.isOn forKey:#"twoplayerswitch"];
[defaults setBool: !tswitch.isOn forKey:#"groupswitch"];
[defaults synchronize];
}
-(void)stateSwitchedgroup:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
//turns two player off when on and soforth
self.twoplayerswitch.on =! tswitch.isOn;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool: tswitch.isOn forKey:#"groupswitch"];
[defaults setBool: tswitch.isOn forKey:#"twoplayerswitch"];
[defaults synchronize];
}
just realised im running this on viewdidload which may be affecting it?
[self.twoplayerswitch setOn:[[defaults objectForKey:#"twoplayerswitch"] boolValue] animated:YES];
[self.twoplayerswitch addTarget:self action:#selector(stateSwitchedtwoplayer:) forControlEvents:UIControlEventValueChanged];
[self.groupswitch setOn:[[defaults objectForKey:#"groupswitch"] boolValue] animated:YES];
[self.groupswitch addTarget:self action:#selector(stateSwitchedgroup:) forControlEvents:UIControlEventValueChanged];
In the stateSwitchedtwoplayer method, you potentially change the state of self.groupswitch.on, but you don't save the change to NSUserDefaults.
In ViewDidLoad
{
NSLog(#"Switch Value %d",delegate.switchvalue);
if(delegate.switchvalue==1)
{
[onoffswitch setOn:YES];
}
else
{
[onoffswitch setOn:NO];
}
}
In Designing,
onoffswitch=[[UISwitch alloc]initWithFrame:(CGRectMake(200, 8, 50, 33))];
[onoffswitch addTarget:self action: #selector(flip:) forControlEvents:UIControlEventValueChanged];
// [onoffswitch setOn:YES];
In Switch Method,
-(IBAction)flip:(id)sender
{
if([sender isOn])
{
[onoffswitch setTag:1];
NSLog(#"%d",[sender tag]);
delegate.switchvalue=[sender tag];
NSLog(#"%d",delegate.switchvalue);
NSLog(#"ON");
NSTimer *BirthTimer=[NSTimer scheduledTimerWithTimeInterval:86400.0 target:self selector:#selector(TimerTapped:) userInfo:nil repeats:YES];
[BirthTimer fire];
}
else
{
NSLog(#"OFF");
}
}
My Problem is,I set the switch mode in ON.If I go to another view,then change again off mode.
Any Idea Please Help me.
Thanks to advance for your help.
Using NSUserDefaults
-(IBAction)flip:(id)sender
{
[onoffswitch setTag:1];
delegate.switchvalue=[sender tag];
NSLog(#"%d",delegate.switchvalue);
if([sender isOn])
{
NSLog(#"ON");
isAlarm=1;
NSLog(#"%d",isAlarm);
NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults]synchronize];
[switchdefault setInteger:delegate.switchvalue forKey:#"Switchcontrol"];
[switchdefault setBool:YES forKey:#"SwitchBool"];
[switchdefault synchronize];
NSTimer *BirthTimer=[NSTimer scheduledTimerWithTimeInterval:86400.0 target:self selector:#selector(TimerTapped:) userInfo:nil repeats:YES];
[BirthTimer fire];
}
else
{
NSLog(#"OFF");
isAlarm=0;
NSLog(#"%d",isAlarm);
}
}
In ViewWillappear
NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];
if([switchdefault boolForKey:#"SwitchBool"])
{
[onoffswitch setOn:YES animated:YES];
}
else
{
[onoffswitch setOn:YES animated:YES];
}
In ViewDidLoad of AnotherView
NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];
if ([switchdefault boolForKey:#"SwitchBool"])
{
delegate.switchvalue=1;
}
[switchdefault synchronize];
Use NSSUserDefault to store the status of your switch button and again while adding it to your view retrieve it from the same...
Store 1 once you switch it ON and the 0 for OFF mode.
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:#"values"];
and get it back like this,
NSInteger mode = [[NSUserDefaults standardUserDefaults] integerForKey:#"values"];
NOTE: I suggest you to add your switch button in the ViewWillAppear/ViewDidAppear.
If you want the switch to be set to delegate.switchValue every time your view appears, try moving this code from viewDidLoad to viewDidAppear:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
if(delegate.switchvalue==1)
{
[onoffswitch setOn:YES];
}
else
{
[onoffswitch setOn:NO];
}
}