开发者

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 ne开发者_运维技巧ed. 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


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];


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


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


In order to set a UISwitch you have to use this [yourSwitch setOn: YES animated: YES];

In order to read the UISwitch you need to retrieve it by the state of the switch which is a boolean type NSLog(@"Switch state :%d", [yourSwitch isOn]);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜