[Swift 5] Recognize ON/OFF of Switch in custom cell for each cell

Introduction

Recently, I tried to make something that I often see, such as enabling the settings in it when I press Switch on the TableView, but I couldn't find any code that worked well. So, this time, I will summarize the code that worked enough to achieve the purpose.

environment

Contents to be implemented this time

Print the following to the console with the print statement

--Tap in the cell → (cell number) th cell was selected --Tap the switch in the cell →(on/off)
→ (Label text in cell) is now (true or false)

If it is a video, it will be as follows. changeSwitch.gif

Preparing a custom cell

First, create a custom cell.

Right click → ** New File ... ** スクリーンショット 2021-01-04 14.29.52.png

Select ** Cocoa Touch Class ** スクリーンショット 2021-01-04 14.30.01.png

The file name is free. This time, set it to "TableViewCell". Don't forget to check ** Also create XIB file **. スクリーンショット 2021-01-04 14.31.00.png

If you can do this, save it in the default location. Next, write the code in TableViewCell.swift.

TableViewCell.swift


import UIKit

class TableViewCell: UITableViewCell {
    
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var uiSwitch: UISwitch!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        
        //Turn off all switches first
        uiSwitch.isOn = false
    }
    
    //Called when the switch is pressed
    @IBAction func changeSwitch(_ sender: UISwitch) {
        if sender.isOn {
            print("on")
        } else {
            print("off")
        }
    }
}

Next, edit the xib file as well. This time it looks like this. Don't forget to associate. スクリーンショット 2021-01-04 14.31.15.png

Set TableView in ViewController

ViewController.swift


import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var table: UITableView!
    var cellContents: Array = ["The first one","Second","Third","4th","Fifth"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Declare dataSource and delegate methods to write in this file
        table.dataSource = self
        table.delegate = self
        
        //Avoid drawing extra cells
        table.tableFooterView = UIView()
        
        //Specify the xib file to use
        table.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
    }
    
    //Set the number of cells to the number of arrays
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellContents.count
    }
    
    //Cell settings
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        
        //Display the contents of the array in order on the cell label
        cell.label.text = cellContents[indexPath.row]
        //IndexPath on switch tag.Enter the value of row
        cell.uiSwitch.tag = indexPath.row
        //Behavior when the switch is pressed
        cell.uiSwitch.addTarget(self, action: #selector(changeSwitch(_:)), for: UIControl.Event.valueChanged)
        
        return cell
    }
    
    //Method called when a cell is pressed
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("\(indexPath.row)The second cell was chosen")
    }
    
    //Set cell width to 80
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    @objc func changeSwitch(_ sender: UISwitch) {
        /*
         sender.The tag contains the position of the switch cell(Int)
         sender.switch on for isOn/off Information is entered(Bool)
The print statement below shows the contents of the label in the cell and the true switch./False
         */
        print(cellContents[sender.tag] + "But\(sender.isOn)Became")
    }
}

Next, we will edit the Storyboard as well. Don't forget to associate this as well. スクリーンショット 2021-01-04 14.31.27.png

Summary

I feel that if you apply it, you can do most of the things. Click here for a project with exactly the same content (https://github.com/leo-30/switchChange)

Reference site

I want to output the text in the cell when switching the switch in the cell

Recommended Posts

[Swift 5] Recognize ON/OFF of Switch in custom cell for each cell
Activate Excel file A1 cell of each sheet in Java
To switch JVM for each project
Best practice to change settings for each environment in iOS app (Swift)
How to switch the display of the header menu for each transition page
[GCD] Basics of parallel programming in Swift
[Java] for Each and sorted in Lambda
Find an approximation of cosx in Swift
The basic basis of Swift custom cells