如何将 UISwitch 放置在 UITableViewCell accessoryView 中?

How to place a UISwitch in an UITableViewCell accessoryView?

我想将 UISwitch 放在 UITableViewCellaccessoryView 中,问题是如果我尝试将它放在 cellForRowAtIndexPath 函数中它可以工作,并且 UISwitch 已正确创建并显示在 UITableViewCell 的右侧,相反,如果我在 func 之外创建它,它将无法工作。我需要在乐趣之外创建它,因为我需要在其他一些功能中检查 UISwitch 的状态并相应地执行代码。

我更好地解释了我对“外部”的意思:使用 Objective-C 你有 @property(ies) 可以让你从当前 class 文件,我们可以在 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
    }
}

如果,而不是:

cell.accessoryView = useAuthenticationSwitch

我使用:

cell.accessoryView = UISwitch()

有效

您还没有打开 UISwitch,因此 useAuthenticationSwitch 将是 UISwitch 类型?而不是 UISwitch 。而是在您的视图 didLoad 中再添加一个额外的代码,并让所有其他代码保持原样

func viewDidLoad() {
   useAuthenticationSwitch = UISwitch() 
}

现在随时随地使用它!

您没有创建 UISwitch

替换为:

weak var useAuthenticationSwitch: UISwitch!

有了这个:

var useAuthenticationSwitch = UISwitch()

希望对您有所帮助。