[英]How to place a UISwitch in an UITableViewCell accessoryView?
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. 我想将一个
UISwitch
在accessoryView
一个的UITableViewCell
,问题是,如果我尝试把它的权利在cellForRowAtIndexPath
而不是如果我创建FUNC它的工作原理和UISwitch正确地创建,并在UITableViewCell的右边显示,它在func之外是行不通的。 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. 我需要在乐趣之外创建它,因为我需要检查其他函数中UISwitch的状态并相应地执行代码。
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
? 我将更好地解释“ 外部 ”的含义:使用
Objective-C
您可以使用@property(ies)
来从当前类文件中的所有位置访问对象,我们可以在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
. 您没有在创建
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? 您尚未打开UISwitch的包装,因此useAuthenticationSwitch的类型将为UISwitch吗? and not UISwitch .
而不是UISwitch。 Instead add one more extra code in your view didLoad and let all the other code be as it is
而是在视图didLoad中添加一个额外的代码,并使所有其他代码保持原样
func viewDidLoad() {
useAuthenticationSwitch = UISwitch()
}
Now use it wherever you want! 现在随时随地使用它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.