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".
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
Step 3: Now we need to add UITableViewCell to our UITableView. Drag UItableViewCell on to UITableView, added in step 2.
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"
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)
- Default state - set image Checkmarkempty
- 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
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.
Comments
Post a Comment
Thank You.