Reputation: 319
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
}
Both startWorkout and infoWorkout cause the application to crash with the error message 'unrecognised selector sent to instance'.
Example of code within the button actions. I am trying to return the indexPath of the button so I can then act on that.
@IBAction func workoutAction(sender: AnyObject) {
let buttonTag = sender.tag
print(buttonTag)
}
exact error message:
016-06-17 18:34:30.722 Exercises[4711:245683] - [Exercises.ExerciseMenu beginWorkout:]: unrecognized selector sent to instance 0x7fb47874a4b0 2016-06-17 18:34:30.727 Exercises[4711:245683] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Exercises.ExerciseMenu beginWorkout:]: unrecognized selector sent to instance 0x7fb47874a4b0'
Upvotes: 3
Views: 941
Reputation: 537
A button within a custom cell cannot call an action that is in the housing view controller. You need to:
1) Move the @IBaction function to the custom cell class
2) Remove the add target code from 'cellFromRowAtIndexPath' and either write that in your custom cell(if you do this you don't need to write @IBAction) or create the connection from the button in storyboard to the @IBAction function
3) Create a delegate for your custom cell
Custom UITableViewCell delegate pattern in Swift
4) Call the delegate from your custom cell for the function you implement in the view controller
**Don't for get you need cell.delegate = self or it will crash when the delegate gets called
ex:
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
}
}
Upvotes: 7