Arun Arun - 3 months ago 19
iOS Question

How to get Text from a label in custom cell in Table View

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = self.tbl_vw.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as!cuscellTableViewCell

cell.txt_lbl.text = self.section[indexPath.row];
cell.sel_btn.addTarget(self, action: #selector(self.switchChanged), forControlEvents: .ValueChanged)

return cell

}



func switchChanged(sender: AnyObject) {
let switchControl: UISwitch = sender as! UISwitch
print("The switch is \(switchControl.on ? "ON" : "OFF")")

if switchControl.on {
print("The switch is on lets martch")
}
}


I have a switch and a label in a custom cell in tableview. When I ON the switch i need to get the text in the label, can any one help how to make it possible.

Answer

Use the tag property of UISwitch to store the position and use it in your handler to get the actual text form section array.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = self.tbl_vw.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as!cuscellTableViewCell

    cell.txt_lbl.text = self.section[indexPath.row];

    cell.sel_btn.tag = indexPath.row

    cell.sel_btn.addTarget(self, action: #selector(self.switchChanged), forControlEvents: .ValueChanged)

    return cell

}



func switchChanged(sender: AnyObject) 
{
  let switchControl: UISwitch = sender as! UISwitch
  print("The switch is \(switchControl.on ? "ON" : "OFF")")

  let text = self.section[switchControl.tag]
  print(text)

  if switchControl.on 
  {
        print("The switch is on lets martch")
  }
} 

If you have multiple sections with multiple rows you can use a dictionary and store a tuple.

var items = [Int:(Int,Int)]()
...

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = self.tbl_vw.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as!cuscellTableViewCell

    cell.txt_lbl.text = self.section[indexPath.row];
    cell.sel_btn.tag = indexPath.row

    let tuple = (section: indexPath.section, row: indexPath.row)
    self.items[cell.sel_btn.hashValue] = tuple
    cell.sel_btn.addTarget(self, action: #selector(self.switchChanged), forControlEvents: .ValueChanged)

    return cell

}

func switchChanged(sender: AnyObject) 
    {
      let switchControl: UISwitch = sender as! UISwitch
      print("The switch is \(switchControl.on ? "ON" : "OFF")")

      let tuple = self.items[switchControl.hashValue]
      print(tuple.0)  // this is the section
      print(tuple.1) // this is the row

      if switchControl.on 
      {
            print("The switch is on lets martch")
      }
    } 
Comments