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.
You have not unwrapped the UISwitch and hence useAuthenticationSwitch will be of type UISwitch? and not UISwitch . Instead add one more extra code in your view didLoad and let all the other code be as it is
func viewDidLoad() {
useAuthenticationSwitch = UISwitch()
}
Now use it wherever you want!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.