xyz code xyz code - 4 months ago 27
Swift Question

Swift: Handle Switch in CustomCell

i want to handle my Switches. How can i save the data if UIswitches is change and update my tableview if changed.

later i want to hide a section when the first switch is changed. so how can i do this in this function?

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

var cell: UITableViewCell!
let row = indexPath.row


///set switch in cells
goingSwitch = UISwitch(frame:CGRectMake(150, 300, 0, 0));
goingSwitch.addTarget(self, action: #selector(ViewController.switchDidChangegoingSwitch(_:)), forControlEvents: .ValueChanged)


eventDaySwitch = UISwitch(frame:CGRectMake(150, 300, 0, 0));
eventDaySwitch.addTarget(self, action: #selector(ViewController.switchDidChangeEventDaySwitch(_:)), forControlEvents: .ValueChanged)



////// Cells
switch(indexPath.section){
case 0:
cell = tableView.dequeueReusableCellWithIdentifier("detailCell", forIndexPath: indexPath)
if row == 0 {
cell.textLabel?.text = "Eventname: xxxx"
cell.detailTextLabel?.text = "okay ausgabe"
}
if row == 1 {
cell.textLabel?.text = "Eventdate: xxxxxxxx"
cell.detailTextLabel?.text = "Eventdate textausgabe"
}
case 1:
cell = tableView.dequeueReusableCellWithIdentifier("goingCell", forIndexPath: indexPath)
if row == 0 {
cell.textLabel?.text = "Can you Go to Event? ???"
cell.accessoryView = goingSwitch
}
if row == 1 {
cell.textLabel?.text = "Is Going: \(guysareGoing)"

}

case 2:
cell = tableView.dequeueReusableCellWithIdentifier("daysCell", forIndexPath: indexPath)
cell.textLabel?.text = eventdays[row]
cell.accessoryView = eventDaySwitch
case 3:
cell = tableView.dequeueReusableCellWithIdentifier("adminCell", forIndexPath: indexPath)
cell.textLabel?.text = others[row]
default:
break
}


// return cell
return cell
}


and here the function from switch.

func switchDidChangegoingSwitch(sender:UISwitch!)
{


if (sender.on == true){
print("goingSwitch is on")
}
else{
print("goingSwitch is off")
}


}


Thanks for help

Answer

You might want to move the codes below to ViewDidLoad

goingSwitch = UISwitch(frame:CGRectMake(150, 300, 0, 0));
goingSwitch.addTarget(self, action: #selector(ViewController.switchDidChangegoingSwitch(_:)), forControlEvents: .ValueChanged)

Then reload the table at switchDidChangegoingSwitch()

Hope it helps.

Jack