ios - 如何将 UISwitch 放置在 UITableViewCell accessoryView 中?

标签 ios swift uitableview uiswitch

我想将 UISwitch 放在 UITableViewCellaccessoryView 中,问题是如果我尝试将它放在正确的位置cellForRowAtIndexPath func 它可以工作,并且 UISwitch 已正确创建并显示在 UITableViewCell 的右侧,相反,如果我在 func 之外创建它,它将无法工作。我需要在乐趣之外创建它,因为我需要在其他一些函数中检查 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
    }
}

如果,而不是:

cell.accessoryView = useAuthenticationSwitch

我使用:

cell.accessoryView = UISwitch()

有效

最佳答案

您没有创建 UISwitch

替换这个:

weak var useAuthenticationSwitch: UISwitch!

有了这个:

var useAuthenticationSwitch = UISwitch()

希望这对您有所帮助。

关于ios - 如何将 UISwitch 放置在 UITableViewCell accessoryView 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31806516/

相关文章:

swift - 从 Sonos 回调 URL 将实时 json 数据发送到 Swift IOS 应用程序以订阅事件

ios - Sqlite.swift 获取行值

ios - 如果 UITableViewCell 包含 cgrect,则以编程方式选择它

android - iOS ARCore - 如何使用 ARCore 连接 Android 和 iOS 设备并发送和接收 AR 对象?

ios - 第一次按按钮不起作用,但第二次就可以了

ios - 确定 zip 中文件的大小?

ios - UIScrollview 从 View 到 View 的动画过渡

ios - 如何不返回 UITableviewCell

ios - Tableview 单元格字幕不显示或应用程序退出

ios - 当 App 进入后台时暂停音频