我有以下自定义UITableViewCell
:
我希望当有人翻转单元格的开关以更新我的模型时,会通知我的视图控制器。我已尝试使用表格视图的委托方法(didSelect
,didFinishEditing
,didHighlight
等),但这些操作都没有调用。有什么办法可以做我想做的事吗?有人请帮忙。
答案 0 :(得分:5)
实际上您的UISwitch已添加到accessoryView
的{{1}},因此请在UITableViewCell
cellforRowAtIndex
并获取var switchView = UISwitch(frame: CGRect.zero)
aCell.accessoryView = switchView
lightSwitch.tag = indexPath.row
switchView.setOn(false, animated: false)
switchView.addTarget(self, action: #selector(switchChanged(_:), for: .valueChanged)
UISwitch
答案 1 :(得分:0)
要在有人翻转单元格的开关时更新模型,您需要:
将此单元格的@IBAction func onSwitched(_ sender: UISwitch)
指定为UISwitch Value Changed
侦听器,如此屏幕截图所示
将颜色模型附加到单元格
cell.myColorModel = myColorModels[indexPath.row]
在@IBAction func onSwitched(_ sender: UISwitch)
中,只需更改模型
selected
属性即可
@IBAction func onSwitched(_ sender: UISwitch) {
myColorModel.selected = sender.isOn
}
完整的源代码
class MyColorModel {
var title: String!
var color: UIColor!
var selected: Bool = false
init(title: String, color: UIColor) {
self.title = title
self.color = color
}
}
class MyColorCell: UITableViewCell {
@IBOutlet weak var colorTitle: UILabel!
@IBOutlet weak var colorImage: UIImageView!
@IBOutlet weak var colorSwitch: UISwitch!
var myColorModel: MyColorModel! {
didSet {
colorTitle.text = myColorModel.title
colorImage.backgroundColor = myColorModel.color
colorSwitch.isOn = myColorModel.selected
}
}
@IBAction func onSwitched(_ sender: UISwitch) {
myColorModel.selected = sender.isOn
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
fileprivate var myColorModels = [MyColorModel(title: "Red", color: UIColor.red),
MyColorModel(title: "Green", color: UIColor.green),
MyColorModel(title: "Blue", color: UIColor.blue)]
@IBAction func onColorsCheck(_ sender: AnyObject) {
for myColorModel in myColorModels {
print("color \(myColorModel.title) \((myColorModel.selected) ? "is checked":"is not checked")")
}
}
// MARK: - UITableView datasource & delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myColorModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyColorCell") as! MyColorCell
cell.myColorModel = myColorModels[indexPath.row]
return cell
}
}