我已經定製UITableViewCell
如下:交換機Tableviews
我想,當有人以更新我的模型翻轉單元的開關通知我的視圖控制器。我嘗試過使用表格視圖的委託方法(didSelect
,didFinishEditing
,didHighlight
等),但是沒有人調用這個動作。有什麼辦法可以做我想做的事嗎?有人請幫忙。
我已經定製UITableViewCell
如下:交換機Tableviews
我想,當有人以更新我的模型翻轉單元的開關通知我的視圖控制器。我嘗試過使用表格視圖的委託方法(didSelect
,didFinishEditing
,didHighlight
等),但是沒有人調用這個動作。有什麼辦法可以做我想做的事嗎?有人請幫忙。
其實你UISwitch已經加入到UITableViewCell
accessoryView
,這樣做就像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
的行動
func switchChanged(_ sender: UISwitch) {
print("which switch is \(sender.tag)")
print("The switch is \(sender?.on ? "ON" : "OFF")")
}
但是,如果你有多個開關,你能得到什麼開關是用這種方法切換? – Adarkas2302
@ Adarkas2302 - 簡單,爲交換機分配標籤 –
要更新模型,當有人翻轉單元的開關您需要:
分配單元的作爲顯示在這個屏幕截圖@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
}
}
除非我希望最後的IBAction方法自動化,否則這是非常有意義的。這可能嗎? –
@NikhilSridhar你對'上次IBAction方法自動化'意味着什麼?'? 「自動化IBAction方法」通過這種方法試圖達到什麼目標? 分享你想解決的問題,然後我們將嘗試找到解決方案。 –
你可以通過通知做到這一點。從您的自定義單元發送通知。或者你可以用'addAction(...)'來完成開關控制。哦,你的標題並沒有描述你想要做什麼(滑塊vs開關;)) – Adarkas2302