Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

swift - "classname has no member functionname" when adding UIButton target

Super newb in Swift and iOS development here.

I am following this tutorial about implementing a custom control in a single view iOS app. It's a Swift 2 tutorial, but so far I'm doing OK transposing everything to 3 as I go (I use XCode 8 Beta).

I have a custom class, RatingControl, connected to a View in the storyboard.

In the class's constructor, I create a button:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.red()

Then, I try to assign an action to the button. The tutorial says I should do it like so:

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), 
for: .touchDown)       

and then create, in the same RatingControl class, the method:

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

But when I compile, it complains:

type "RatingControl" has no member "ratingButtonTapped"

I've made 100% sure the function is there, in the class, and properly named. Full source

Is there something obvious I'm missing?

What I tried:

  • Added @objc to the class definition as per this answer (but that seems weird for a Swift-only thing, no?)

  • Made ratingButtonTapped() explicitly public (but that doesn't look like it should be necessary)

  • Fiddled around with strings instead of selectors, button.addTarget(self, action: "RatingControl.ratingButtonTapped", for: .touchDown) and many more, but that just crashes it later.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Swift 3, method reference for: func ratingButtonTapped(button: UIButton) becomes ratingButtonTapped(button:).

So, using #selector(RatingControl.ratingButtonTapped(button:)) also work.

And if you want to keep #selector(RatingControl.ratingButtonTapped(_:)), then you need to declare the ratingButtonTapped method as:

func ratingButtonTapped(_ button: UIButton) { //<- `_`
    print("Button pressed ??")
}

And if you have only one ratingButtonTapped method in the class, you can address the selector as #selector(RatingControl.ratingButtonTapped) or simply (from inside RatingControl class) #selector(ratingButtonTapped).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...