Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone setting and reading state UISwitch

I have a view in which its objects are set from a database and likewise saved to a database. The UITextViews are working great, but I cannot seem to find out how to set the state of a UISwitch.

I can change it in the IB but that isnt what I need. The record in the DB has a 0 or 1 boolean. So if the field is true then I want to set the state of the UISwitch to ON.

Also when I save the record, I need to be able to look at the value on the view, and thus set the field on my table.

thanks for any help!!

EDIT: This is what I have done so far:

.h file

@interface UserEdit : UIViewController {


    IBOutlet UISwitch *male;

}


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

.m file

@synthesize male;


- (void)viewDidLoad {
    [super viewDidLoad];

    [male SetOn:NO];


}

the app dumps when it hits the SetOn line above

I also need to be able not only set the value, but read it too

like image 350
Mark Worsnop Avatar asked May 22 '11 20:05

Mark Worsnop


3 Answers

You can set the state of a UISwitch either via the on or setOn:animated: methods, depending on your requirement.

e.g.: [yourUISwitch setOn:YES];

Check the Setting the Off/On State section of the UISwitch Class Reference for more info.

UPDATE

As per the docs, you can read the value via [yourUISwitch isOn];

like image 102
John Parker Avatar answered Oct 06 '22 11:10

John Parker


You can do it the following way:

//
//  ViewController.m
//


#import "ViewController.h"


@interface ViewController ()

@property (weak, nonatomic) IBOutlet UISwitch *mySwitch;

- (IBAction)switchChanged:(id)sender;

@end


@implementation ViewController

- (IBAction)switchChanged:(id)sender
{
    [[NSUserDefaults standardUserDefaults] setBool:self.mySwitch.on forKey:@"SwitchState"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.mySwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"SwitchState"];

}

@end
like image 28
Painted Black Avatar answered Oct 06 '22 09:10

Painted Black


There is the swift version code to setting and reading UISwitch's state

    //Change switch state
    self.mSwitchAccept.setOn(true, animated: true)
    //Get the switch state
    let switchState : Bool = self.mSwitchAccept.on
like image 41
Kevin ABRIOUX Avatar answered Oct 06 '22 09:10

Kevin ABRIOUX