iOS programmatically create UISwitch

UISwitch is a view that is lets the user select a YES or NO much like a checkbox. You can set the initial state of the Switch and with the help of the target action for a change event you can find out if the current state of the switch is ON or OFF.

iOS programmatically create UISwitch

Interface file for the view controller - MySwitchViewController.h

#import <UIKit/UIKit.h>

@interface MySwitchViewController : UIViewController

@property (nonatomic, strong) UISwitch *mySwitch;

@end

Implementation file for the view controller - MySwitchViewController.m

#import "MySwitchViewController.h"

@interface MySwitchViewController ()

@end

@implementation MySwitchViewController

@synthesize mySwitch;

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    
    //set the view background to white
    self.view.backgroundColor = [UIColor whiteColor];
    
    //frame for the switch
    CGRect myFrame = CGRectMake(10.0f, 10.0f, 250.0f, 25.0f);
    //create and initialize the slider
    self.mySwitch = [[UISwitch alloc] initWithFrame:myFrame];
    //set the switch to ON 
    [self.mySwitch setOn:YES];
    //attach action method to the switch when the value changes
    [self.mySwitch addTarget:self
                action:@selector(switchIsChanged:)
                forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:self.mySwitch];
}

//check if the switch is currently ON or OFF
- (void) switchIsChanged:(UISwitch *)paramSender{
    
    if ([paramSender isOn]){
        NSLog(@"The switch is turned on.");
    } else {
        NSLog(@"The switch is turned off.");
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Reference


4 comments :

  1. A tiny gratefulness cheap fifa 14 coins can give us a lasting positive mood, which requires our consciousness fifa 14 coins and gratefulness. Then with a heart of gratefulness, everything turns out to be fifa 14 coins gorgeous.

    ReplyDelete