在Swift的UITableView单元格中添加开关 [英] Add switch in UITableView cell in Swift

查看:129
本文介绍了在Swift的UITableView单元格中添加开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift的tableView单元中以编程方式嵌入UISwitch? 我就是这样

How can I embed a UISwitch programmatically in a tableView cell in Swift? I'm doing it like that

let shareLocationSwitch = UISwitch()
cell.accessoryView = shareLocationSwitch

推荐答案

这是将UISwitch嵌入到UITableView单元格中的方法.

Here is way you can embed a UISwitch on a UITableView cell.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        
                var cell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifire", for: indexPath) as! YourCellClass

                       //here is programatically switch make to the table view 
                        let switchView = UISwitch(frame: .zero)
                        switchView.setOn(false, animated: true)
                        switchView.tag = indexPath.row // for detect which row switch Changed
                        switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                        cell.accessoryView = switchView

               return cell
      }

这是切换呼叫贝克方法

func switchChanged(_ sender : UISwitch!){

      print("table row switch Changed \(sender.tag)")
      print("The switch is \(sender.isOn ? "ON" : "OFF")")
}

@LeoDabus Great! explanation.

注意:如果您的tableview可能有多个section,则应创建一个CustomCell子类UITableViewCell,并在UITableViewCell awakeFromNib方法内而不是表视图中配置accessoryView c10>方法.将可重用的cell出队时,将其投射到CustomCell 此处为示例来自@LeoDabus

Note: if your tableview may have more than one section then You should create a CustomCell subclassing UITableViewCell and configure your accessoryView inside UITableViewCell awakeFromNib method instead of table view cellForRowAt method. When dequeuing the reusable cell cast it to your CustomCell Here is sample from @LeoDabus

这篇关于在Swift的UITableView单元格中添加开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆