我有这个 TableView :
但我无法识别用户何时选择行中的 UISwitch。 我知道我需要 UITableViewCell 类中的 @IBAction,但我没有找到适合我的指南。 我想在用户单击 UISwitch 时打印该行的索引路径。
这是我的单元格类(class):
class TicketsFilterCell: UITableViewCell {
@IBOutlet weak var textFilter: UILabel!
@IBOutlet weak var switchFilter: UISwitch!
class var reuseIdentifier: String? {
get {
return "TicketsFilterCell"
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
我该怎么办?
提前致谢。
编辑
我的cellForRowAtIndexPath:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: TicketsFilterCell? = tableView.dequeueReusableCellWithIdentifier("cellTicketFilter", forIndexPath: indexPath) as? TicketsFilterCell
cell?.delegate = self
if(indexPath.section == 0) {
let text = status[indexPath.row]?.capitalizedString
cell?.textFilter.text = text
} else if(indexPath.section == 1) {
let text = queues [indexPath.row]?.capitalizedString
cell?.textFilter.text = text
} else if(indexPath.section == 2) {
let text = types[indexPath.row]?.capitalizedString
cell?.textFilter.text = text
} else if(indexPath.section == 3) {
let text = severities[indexPath.row]?.capitalizedString
cell?.textFilter.text = text
}
return cell!
}
最佳答案
次元,
这是你可以做的:)
在您的单元类中声明一个协议(protocol),我们将其称为 CellProtocol。
protocol CellProtocol : class {
func switchButtonTapped(WithStatus status : Bool, ForCell myCell : TicketsFilterCell)
}
在 TicketsFilterCell 类中声明一个变量来保存委托(delegate),
weak var delegate : CellProtocol!
当用户点击您的开关时,将触发委托(delegate):
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.delegate .switchButtonTapped(WithStatus: selected, ForCell: self)
}
在您的 TableViewController 中使用
确认协议(protocol)class ViewController: UITableViewController,CellProtocol {
现在,在 ViewController 的 cellForRoAtIndexPath 中,为每个单元格将委托(delegate)设置为 self。
cell.delegate = self
最后实现委托(delegate)方法如下
func switchButtonTapped(WithStatus status: Bool, ForCell cell: TicketsFilterCell) {
let indexPath = self.tableView .indexPathForCell(cell)
print("cell at indexpath \(indexPath) tapped with switch status \(status)")
}
编辑:
对于您已拖动 IBOutlet 进行切换的每个单元格:) 现在您需要的只是从 UISwitch 到单元格的 IBAction :)
@IBAction func switchTapped(sender: UISwitch) {
self.delegate.switchButtonTapped(WithStatus: sender.on, ForCell: self)
}
就是这样:)
关于ios - UISwitch - UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37723672/