How to Add On/Off Button Like Airplane Mode And Bluetooth Using UISwitch

0
Shares
How to Add On/Off Button Like Airplane Mode And Bluetooth Using UISwitch
Rate this post

We all have used UISwitch in one way or another, either to turn on/off Airplane mode or WiFi/Bluetooth in our devices. The Switch is basically a class that helps to create such buttons.

And today, in our iOS app tutorial, we’ll be sharing the implementation process of UISwitch to add on/off buttons for your iphone app development. And in case you don’t know how to create an app in iphone, you can go through our series of iOS app tutorials for the same.

Let’s Get Started

Open your Xcode and create a new project under file menu.

sampleswitch1

In the next tab, select Single View Application.

sampleswitch2

Write your project name and other details and click on Next.

sampleswitch3

Once you create a new project, go to Main.Storyboard and select ViewController.

sampleswitch4

Now drag and drop UISwitch from “Show the object library” section.

sampleswitch5

sampleswitch6

Now select see the attribute inspector which have properties for switch. We can manage the default state, tint color, background, custom image, alignment etc.

Now we set outlet UISwitch in ViewController.

@IBOutlet weak var swOnOff: UISwitch!

Now we add the target to UISwitch.

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

//Add Target for UISwitch
swOnOff.addTarget(self, action: #selector(stateChanged(_:)), forControlEvents: .TouchUpInside)
}

func stateChanged(switchState: UISwitch) {
if swOnOff.on {
//Switch On
} else {
//Switch Off
}
}

We can also manage it by simple button event too.

Take a button and set outlet and action for the same.

//Outlet
@IBOutlet weak var btnSwitch: UIButton!
//MARK: Defination for switch ON/Off button action
@IBAction func actionSwitch(sender: AnyObject) {
if swOnOff.on {
swOnOff.setOn(false, animated: true)
btnSwitch.setTitle("Switch ON", forState: .Normal)
} else {
swOnOff.setOn(true, animated: true)
btnSwitch.setTitle("Switch Off", forState: .Normal)
}
}

And done!

simulator-screen-shot-jan-16-2017-3-10-12-pm

Easy and Simple. And now that you know the process for implementing Switch, you can add it for different functionalities in your app. Although, it’s also possible to customize the Switch class, but it’s bit difficult. So if your desire is to add customized Switch, or need to hire iPhone app developer for your project, consider UISwitch for providing on/off button function.

Grab a free copy of Switch demo example from Github.

 
0
Shares
 

LET'S TALK VALIDATE YOUR IDEA!

Leave a Reply

Your email address will not be published. Required fields are marked *