iOS – UISwitch example…

UISwitch is an component which resembles the electronic switch with animation.We can change the Switch state by manually or programatically.

In this tutorial we are going to change the state of the UISwitch programatically with suitable changing Label text.Lets have a look at this,

Step 1: Create a new ‘Single view’ project in Xcode.

Step 2: Drag and drop components like UISwitch,UILabel and UIButton.Arrange them as shown below,

Step 3:  Right click over the ‘UISwitch’ component.Now drag and drop in the .h file as shown below.Give a name to your UISwitch and UILabel component which will be referenced later.Set method name for the UISwitch and Button as we did before.

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

@property (weak, nonatomic) IBOutlet UILabel *switchLabel;

- (IBAction)toggleAction:(id)sender;

- (IBAction)switchAction:(id)sender;

Step 4: Include this method in your .m file.

- (IBAction)toggleAction:(id)sender {

    if(switchObject.on)

    {

        [switchObject setOn:NO animated:YES];

                       switchLabel.text  = @"Disabled";

    }

    else

    {

 [switchObject setOn:YES animated:YES];

        switchLabel.text  = @"Enabled";

            }

}

In this method the UISwitch state and label value changes when user pressed the ‘Toggle’ button.

Step 5:Include this method in your .m file.

- (IBAction)switchAction:(id)sender {

    if(switchObject.on)

    {

       switchLabel.text  = @"Enabled";

    }

    else

    {

        switchLabel.text  = @"Disabled";

        }

}

In this method the label value changes when user pressed the UISwitch.

Step 6: Now Run the project.You are done…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s