在Swift的UITableView单元格中添加开关

编程入门 行业动态 更新时间:2024-10-04 13:31:55
本文介绍了在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单元格中添加开关

本文发布于:2023-11-26 10:02:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633647.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元格   Swift   UITableView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!