Nazmul Hasan Nazmul Hasan -4 years ago 106
Swift Question

How can I get text from row in the UITableView?

unfortunately I can not use tag value to get switch Changed row detected ... Mainly I need to know particular switch changed row text "bad morning" to search something from my array . so anyone help me please how can I get

cell textLabel text
in the switchChanged method . Thanks

Code sample :

func switchChanged(_ sender : UISwitch!){

print("table row switch Changed \(sender.tag)")
print("The switch is \(sender.isOn ? "ON" : "OFF")")
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


var cell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifire", for: indexPath) as! YourCellClass

cell.textLabel?.text = "bad morning"

let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)

switchView.tag = indexPath.row // for detect which row switch Changed

switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)

cell.accessoryView = switchView

return cell

}

Answer Source

You can add a delegate to your YourCellClass. When the switchView is toggled, call a delegate method something like this

class YourCellClass: UITableViewCell {
    weak var delegate:YourCellClassDelegate?
    var switchView: UISwitchView

    init() {
        ...other stuff...
        switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
        ...other stuff...
    }

    func switchChanged(_ sender : UISwitch!){ 
        if let delegate = delegate {
            delegate.cellDidToggleSwitch(self, isOn: sender.isOn)
        }
    }
}

protocol YourCellClassDelegate {
    func cellDidToggleSwitch(_ cell: YourCellClass, isOn: Bool)
}

Then in the ViewController with the TableView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {  // specific row showing switch          
        var cell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifire", for: indexPath) as! YourCellClass
        cell.textLabel?.text = "bad morning"
        cell.delegate = self
        return cell
    }
    return UITableViewCell()
}

func cellDidToggleSwitch(_ cell: YourCellClass, isOn: Bool) {
    //here's your cell
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download