如何在UITableViewCell accessoryView中放置UISwitch?

Alu*_*num 0 uitableview uiswitch ios swift

我想UISwitch在a accessoryView中放置一个UITableViewCell,问题是如果我尝试将它放在cellForRowAtIndexPathfunc中它正常工作并且UISwitch正确创建并显示在UITableViewCell的右侧,而不是我在外面创建它功能它将无法正常工作.我需要在有趣的地方创建它,因为我需要在其他函数中检查UISwitch的状态并相应地执行代码.

我更好地解释了我对" 外部 "的意思:Objective-C你可以@property(ies)让你从当前类文件中的任何地方访问对象,我们可以实现同样的目的Swift吗?

这是我的代码:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果,而不是:

cell.accessoryView = useAuthenticationSwitch
Run Code Online (Sandbox Code Playgroud)

我用:

cell.accessoryView = UISwitch()
Run Code Online (Sandbox Code Playgroud)

有用

Luc*_*tti 5

你没有创造UISwitch.

替换这个:

weak var useAuthenticationSwitch: UISwitch!
Run Code Online (Sandbox Code Playgroud)

有了这个:

var useAuthenticationSwitch = UISwitch()
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.