Skip to main content

Add Custom Checkbox on UITableViewCell or UITableView in Swift 4

Add Custom Checkbox


Introduction to how to add custom checkbox on UITableViewCell or UITableView in swift 4

In this tutorial, we are going to learn about how can we create or add custom checkbox on UITableViewCell or UITableView in swift and perform IBAction on our custom checkbox placed on UITableViewCell or UITableView in swift 4. We will place UIButton on UITableViewCell that will act as checkbox for our UITableViewCell in UITableView using swift 4. In the end of this tutorial, we will have output as shown in below picture
Learn how to create checkbox in swift from HERE

Steps to create or add custom checkbox on UITableViewCell or UITableView

Step 1 : Create a new Xcode project and select "Single View App" template. Name  project as "addCheckBoxonTable-Tutorial".

Add custom checkbox on UITableViewCell or UITableView in swift 4
Step 2: Open "Main.storyboard" file and drag UITableView object on to the view. Then we will add constraints to UITableView so that it fits to our screen size. Please follow the steps as shown in the below picture

Add custom checkbox on UITableViewCell or UITableView in swift 4

Step 3: Now we need to add UITableViewCell to our UITableView. Drag UItableViewCell on to UITableView, added in step 2.

Add custom checkbox on UITableViewCell or UITableView in swift 4

Step 4: Select UITableViewCell and select option "Size inspector" (option will  be on right hand side of your screen) change the height to 100.0 and background color to yellow, will get it changed from "Attribute inspector". Also change the UITableView Row height to 100.0 also. Change UITableViewCell identifer ro "CheckBoxCell"

Add custom checkbox on UITableViewCell or UITableView in swift 4
Add custom checkbox on UITableViewCell or UITableView in swift 4
Add custom checkbox on UITableViewCell or UITableView in swift 4
Step 6:  Drag UILable and UIButton (this UIButton will act as checkbox for our cell in UITableview) to content view of UITableViewCell. Add constraints to both object 

  • UILable constraint: (Top = 0, Bottom = 0, Leading = 10, Trailing = 10 w.r.t. UIButton)
  • UIButton constraint: (Trailing = 10, height = 50, width = 50, align center Y to superview)
Step 7: Add images to your project. Download images from Archive-CheckBoximages.zip. Change UIButton type to custom and remove title. Set images to UIButton as follows

  1. Default state - set image Checkmarkempty
  2. Selected state - set image Checkmark

You can change state of UIButton by changing "State config" property in attribute inspector.

Step 8: Set tag for UILable  = 1 and for UIButton = 2. You will find this property under attribute inspector too.

Step 9: Open ViewController.swift. Here we will create IBOutlet for UITableView first and connect it with UITable in "Main.storyboard". Then we will write down UITableViewDatasource methods for our UITableView.  Below is the complete code for ViewController.swift file

//
// ViewController.swift
// addCheckBoxonTable-Tutorial
//
// Created by Aman Aggarwal on 2/1/18.
// Copyright © 2018 iostutorialpoint.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tblList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tblList.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CheckBoxCell")
if let lbl = cell?.contentView.viewWithTag(1) as? UILabel {
lbl.text = "item-\(1)"
}
if let btnChk = cell?.contentView.viewWithTag(2) as? UIButton {
btnChk.addTarget(self, action: #selector(checkboxClicked(_ :)), for: .touchUpInside)
}
return cell!
}
@objc func checkboxClicked(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


In above code, we write down UITabelViewDataSource methods. numberOfRows and cellForRow,in cellForRow we get UILabel using the tags we set in prototype cell, same for UIButton. Lastly, we add target to UIButton. In the selector, we set sender selected property to the opposite of its  current elected property. In more clear word if UIButton has state not selected (state other than selected state) then we make it selected and vice-versa.

Where to go from here

In this tutorial, we learned how to add checkbox on UITableViewCell in swift 4. We use UIButton to act as custom checkbox and then ad target to it in cellForRow method. You can grab the copy of source code from addCheckBoxonTable-Tutorial.zip.


Comments

Popular Posts

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

Master Map & Filter, Javascript’s Most Powerful Array Functions

Master Map & Filter, Javascript’s Most Powerful Array Functions Learn how Array.map and Array.filter work by writing them yourself This article is for those who have written a  for  loop before, but don’t quite understand how  Array.map  or  Array.filter  work. You should also be able to write a basic function. By the end of this, you’ll have a complete understanding of both functions, because you’ll have seen how they’re written. Array.map Array.map  is meant to transform one array into another by performing some operation on each of its values. The original array is left untouched and the function returns a new, transformed array. For example, say we have an array of numbers and we want to  multiply each number by three . We also don’t want to change the original array. To do this without  Array.map , we can use a standard for-loop. for-loop var originalArr = [1, 2, 3, 4, 5]; var newArr = []; for(var i = 0; i < originalArr.length; i+...