Saturday, April 18, 2015

Toggle Button using setTitle()

1. Drag a button to the storyboard. Make the text as "OFF".

2. Control-drag the button to ViewController.swift and make it an IBAction:

    @IBAction func myButton(sender: AnyObject) {
    }

3. Complete the code as below:

import UIKit

class ViewController: UIViewController {

    @IBAction func myButton(sender: AnyObject) {
        
        if (sender.titleLabel!?.text == "ON")
        {
            sender.setTitle("OFF", forState:  UIControlState.Normal);
        }
        else
        {
            sender.setTitle("ON", forState:  UIControlState.Normal);
        }
    }

========================

No comments:

Post a Comment