How to use addTarget / #selector in Swift3

Hi! I'm following the instructions on this page (https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson5.html#//apple_ref/doc/uid/TP40015214-CH19-SW1) to make the app FoodTracker, but I constantly have trouble on this line:


button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)


Everytime I write the code down Xcode tells me that there's no member such as ratingButtonTapped thing 😟

I tried everything to prove this code works; l updated both Xcode and Swift, I looked for the solutions on the Internet, and so on. But everything didn't work.


I need help. Please.


Thank you.

did you check that's there is no typing error in the method name, such as an uppercase ?

Yup, no typos at all. But still, thank you for your response!

Accepted Answer

I assume you surely have put some code following this part:


To add an action to the button

1. In

RatingControl.swift
, before the last curly brace (
}
), add the following:
// MARK: Button Action

2. Under the comment, add the following:

func ratingButtonTapped(button: UIButton) {
  print("Button pressed   ")
}


If you are sure you put that code exactly the same as the tutorial, you may need to modify it as:

func ratingButtonTapped(_ button: UIButton) {
  print("Button pressed   ")
}


You know the tutorial is written for Swift 2, and you should know that even in Swift 2 it has some flaws.

You better search a better tutorial written for Swift 3.

Hi OOPer,


OMG Thank you sooooooo much for your advice. It works!

Hope Apple updates this tutorial as soon as possible. I'm new here and and this is the best tutorial I've seen so far, unfortunately 😝

Again, thank you for your advice.


Christine.

Thank you so much!

OOPer's answer is not for me.


but I changed to: button.addTarget(self,action:"ratingButtonTapped:",forControlEvents:.TouchDown), it works

How to use addTarget / #selector in Swift3
 
 
Q