Friday, 24 June 2016

How to create CheckBox buttons in ios swift2 Tutorial

For CheckBox Buttons there is nothing that comes built in Xcode iOS Swift2.

CheckBoxes

      You can yourself implement Checkboxes easily. You can set an unchecked_checkbox for your button for StateNormal and a checked_checkbox for your StateSelected. Now on taps the button will change its image and alternate between checked and unchecked image.

Steps to start designing RadioButtons

  1. Create new project in Xcode,Start up Xcode and go to File\New\Project. Select iOS\Application\Single View Application, and click Next. 

  2.  Create a custom class.

    • CheckBox.swift

     import UIKit

    class CheckBox: UIButton {
      
        //images
        let checkedImage = UIImage(named: "checked_checkbox")
        let unCheckedImage = UIImage(named: "unchecked_checkbox")
      
        //bool propety
        @IBInspectable var isChecked:Bool = false{
            didSet{
                self.updateImage()
            }
        }

      
        override func awakeFromNib() {
           // self.addTarget(self, action:#selector(CheckBox.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
            self.updateImage()
        }
      
      
        func updateImage() {
            if isChecked == true{
                self.setImage(checkedImage, forState: .Normal)
            }else{
                self.setImage(unCheckedImage, forState: .Normal)
            }

        }

        func buttonClicked(sender:UIButton) {
            if(sender == self){
                isChecked = !isChecked
            }
        }

    }

     3.ADD two images with name

    • checked_checkbo.png

    • unchecked_checkbox.png

     4.In storyboard 

    1. Drag and drop 3 buttons.
    2. Select button1,got to identity inspector and select the custom class as CheckBox.
    3. Repeate,steps 2 for button2,button3.

     

    5.Finally,run the xcode and check the output,its worked for me,thanks for following tutorial

No comments:

Post a Comment