I would like to place an UISwitch
in a accessoryView
of a UITableViewCell
, the problem is that if I try to place it right in the cellForRowAtIndexPath
func it works and the UISwitch is correctly created and displayed at the right of the UITableViewCell, instead if I create it outside of the func it won't work. I need to create it outsite of the fun because I need to check the status of the UISwitch in some other func and execute code accordingly.
I explain better what I mean for "outside": with Objective-C
you have @property(ies)
that lets you access objects from everywhere inside the current class file, can we achieve the same thing in Swift
?
This is my code:
import UIKit
class ConfigurationViewController: UITableViewController, UITextFieldDelegate {
weak var useAuthenticationSwitch: UISwitch!
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
if indexPath.section == 0 {
if indexPath.row == 0 {
cell.textLabel!.text = "Use Authentication"
cell.accessoryView = useAuthenticationSwitch
}
} else {
}
return cell
}
}
If, instead of:
cell.accessoryView = useAuthenticationSwitch
I use:
cell.accessoryView = UISwitch()
It works
You are not creating the UISwitch
.
Replace this:
weak var useAuthenticationSwitch: UISwitch!
With this:
var useAuthenticationSwitch = UISwitch()
Hope this helps.