Reputation: 167
i have a UITableviewcell with a label and switch.
cell label have dynamic values according to situation.
when i on/off switch. it just shows tag that which row switch state is changed. but i want to get exactly what is on label where switch is on/off.
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
//switch value change function
@objc func switchChanged(_ sender : UISwitch!){
print("table row switch Changed \(sender.tag)")
//looking for label text on this tag
}
is there any way to get cell label value when switch state changed inside tableview cell.
Upvotes: 1
Views: 1121
Reputation: 1130
declare following closure variable in UItableViewCell
var returnBlock: ((String?)-> Void)?
and in switch method just call it with labelObj.text
@objc func switchChanged(_ sender : UISwitch!){
returnBlock?(labelObject.text)
}
In TableViewController - CellForRowAtIndexPath method where you return cell before that write following code.
cell.returnBlock = { labelText in
if let value = labelText {
print(value)
}
}
There is many ways to do, but i think this is proper way.
For default UITableViewCell
@objc func switchChanged(_ sender : UISwitch!){
if let cellObj = tableView.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? UITableViewCell {
print(\(cellObj.labelObj.text ?? ""))
}
}
Upvotes: 2