所以我有一个 UITableViewCell:
代码如下:
import Foundation
import UIKit
class Cell_Switch: UITableViewCell{
@IBOutlet weak var label: UILabel!
@IBOutlet weak var select: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override var layoutMargins: UIEdgeInsets {
get { return UIEdgeInsetsZero }
set(newVal) {}
}
@IBAction func onSwitch(sender: AnyObject) {
//I don't want to respond here!!!
}
}
这是 UITableView 代码:
import Foundation
import UIKit
class PreferencesInterestedDays: UIViewController,UITableViewDataSource,UITableViewDelegate{
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
var nib = UINib(nibName: "Cell_Switch", bundle: nil)
table.registerNib(nib, forCellReuseIdentifier: "Cell_Switch")
table.separatorInset = UIEdgeInsetsZero
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:Cell_Switch = self.table.dequeueReusableCellWithIdentifier("Cell_Switch") as Cell_Switch
//what do I do here???
//not working: cell.select.actionsForTarget(self, forControlEvent: UIControlEvents.ValueChanged)
return cell
}
//this event doesn't fire!
@IBAction func onSwitch(sender: AnyObject) {
//doesn't work... ;(
println("Hello!")
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
table.deselectRowAtIndexPath(indexPath, animated: false)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 7
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44.0
}
}
这是它的样子:
所选的每个开关都有不同的响应。我需要在 UITableView 类中处理操作(并获取行号),而不是在 UITableViewCell 类中...
怎么办?
XCode 6.2、iOS 8.2
最佳答案
简单的解决方案是
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:Cell_Switch = self.table.dequeueReusableCellWithIdentifier("Cell_Switch") as Cell_Switch
cell.select.addTarget(self, action: Selector("onSwitch:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
}
@IBAction func onSwitch(sender: AnyObject) {
println("Hello!")
}
请注意,删除 Cell_Switch
中对 IBAction 的所有引用。
干杯。
关于ios - 响应 UIViewController 中的表格单元格操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29029918/