func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - UITableViewCell { let cellIdentifier = "ExerciseMenuCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "ExerciseMenuCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ExerciseOptionTableViewCell let currentWorkout = workouts[indexPath.row] cell.nameLabel!.text = currentWorkout.name cell.photoImageView.image = currentWorkout.filename cell.startWorkout.tag = indexPath.row cell.startWorkout.addTarget(self, action:Selector("workoutAction:"), forControlEvents: .TouchUpInside) cell.infoWorkout.tag = indexPath.row cell.infoWorkout.addTarget(self, action:Selector("infoAction:"), forControlEvents: .TouchUpInside) return cell }
startWorkout和infoWorkout都会导致应用程序崩溃,并显示错误消息“无法识别的选择器已发送到实例”.
按钮操作中的代码示例.我试图返回按钮的indexPath,然后我可以采取行动.
@IBAction func workoutAction(sender: AnyObject) { let buttonTag = sender.tag print(buttonTag) }
确切的错误信息:
016-06-17 18:34:30.722练习[4711:245683] – [Exercises.ExerciseMenu beginWorkout:]:无法识别的选择器发送到实例0x7fb47874a4b0
2016-06-17 18:34:30.727练习[4711:245683] ***由于未捕获的异常’NSInvalidArgumentException’终止应用程序,原因:’ – [Exercises.ExerciseMenu beginWorkout:]:无法识别的选择器发送到实例0x7fb47874a4b0′
1)将@IBaction函数移动到自定义单元类
2)从’cellFromRowAtIndexPath’中删除添加目标代码,并将其写入自定义单元格(如果这样做,则不需要编写@IBAction)或创建从故事板中的按钮到@IBAction函数的连接
3)为您的自定义单元格创建一个委托
Custom UITableViewCell delegate pattern in Swift
4)从您的自定义单元格中调用您在视图控制器中实现的功能的代理
**不要让你需要cell.delegate = self或者在调用委托时它会崩溃
例如:
CustomCell.swift
protocol CustomCellDelegate { func pressedButton() } class CustomCell: UITableViewCell { var delegate: CustomCellDelegate! @IBAction func buttonPressed(sender: UIButton) { delegate.pressedButton() } }
ViewController.swift
class CustomClass: UIViewController, CustomCellDelegate { func pressedButton() { // Perform segue here } }