Why UIButton.addTarget needs a ":" after the string representing the action? - ios

I have the following code:
button.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)
Why do I need the ":" after the string for action?

It comes from Objective-C. Basically it means that the action method takes a parameter. In your case the parameter passed will be the sender (i.e. the UIButton that generated the action to be called.

because your function buttonIsPressed has 1 parameter.
one : equal to one parameter

U dont need it. But then you have to have function that takes no parameters.
func buttonIsPressed(){
println("button pressed")
}

Related

When adding target to button, why must target action be an objc func? [duplicate]

This question already has an answer here:
Why is the #objc tag needed to use a selector?
(1 answer)
Closed 4 years ago.
Why does a button action need to be a function declared with objc? Im curious as to what the difference is between an objc func and a func and why a button can't simply reference it's action to a func.
Edit: I am using Swift. Thank you very much for your time.
var thisButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(thisFunction), for: .touchUpInside)
return button
}()
#objc func thisFunction() {
//stuff
}
Swift generates code that is only available to other Swift code, but
if you need to interact with the Objective-C runtime – all of UIKit,
for example – you need to tell Swift what to do.
That’s where the #objc attribute comes in: when you apply it to a
class or method it instructs Swift to make those things available to
Objective-C as well as Swift code. So, any time you want to call a
method from a UIBarButtonItem or a Timer, you’ll need to mark that
method using #objc so it’s exposed – both of those, and many others,
are Objective-C code.
Refer :
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html

swift 3 selector with arguments

I searched a lot for selector method in Swift 3, but I have lots of confusion for it.
1) what is difference between Selector & #selector?
2) if I write with Selector, the function is outlined means not available?
3) How to pass a parameter with #selector method.
My code
let button = UIButton()
button.addTarget(self, action: #selector(getData(_:true)), for: .touchUpInside)
button.addTarget(self, action: Selector(), for: .touchUpInside)
func getData(_ isShowing:Bool){
}
Can you help me to clear my confusion?
Thank you for your valuable time
Answers to your questions:
Selector is a type. (to indicate that it's a function type). Whereas #selector is to call a function. #selector --> will return Selector type. #selector checks if there is any function exist with that function name
First answer will clarify this
You can send value through sender like this. Example: button.layer.setValue(forKey:"someKey")
I believe #selector is just a language construction that creates an object of type Selector. You want to use #selector as the compiler actually checks if the method exists anywhere, where with Selector("abc") you just run the constructor and it's not validated.

Swift 2.2 Selector with multiple arguments - actually passing in

I want to use a selector, but I need to pass in the arguments
I understand the syntax follows:
#selector(class.method(_:paramName:))
but i need to actually pass in parameters. How do I do this?
Here's my attempt:
exploreTap = UITapGestureRecognizer(target: self, action: #selector(MainViewController.showViewWithIdentifier(_:exploreView,id:"explore")))
You cannot pass parameters to selectors, selector is just a method name, nothing else. You are not calling the method so you cannot pass parameters.
Just call the necessary code inside your tap handler.
func onTap() {
MainViewController.showViewWithIdentifier(exploreView, id:"explore")
}
and then
UITapGestureRecognizer(target: self, action: #selector(onTap))

What is the proper syntax for action in swift 2?

I have a function set like this:
func alertControllerBackgroundTapped(myString: String) {
///do something in here
})
}
which I am trying to invoke here:
alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action:#selector(CICViewController.alertControllerBackgroundTapped(_:))))
But obviously this will gives me an error since I am not setting my arguments (myString) correctly.
What is the proper syntax in this?
many thanks
Since you are adding this action to UITapGestureRecognizer, the action must have a proper signature - a single-argument function taking UITapGestureRecognizer and not returning anything. Inside the recognizer body you are free to make a call to your function that takes a string:
func handleTap(recognizer: UITapGestureRecognizer) {
alertControllerBackgroundTapped("Hello!")
}
Add handleTap as the action instead of alertControllerBackgroundTapped:
alert.view.superview?.addGestureRecognizer(
UITapGestureRecognizer(
target: self
, action:#selector(CICViewController.handleTap(_:))
)
)

Proper way to use selectors in Swift

I'm creating a view programatically, and adding a function so the action responds to the UIControlEvents.TouchUpInside event:
button.addTarget(self, action: action, forControlEvents:
UIControlEvents.TouchUpInside)
So, by going into the documentation I've added this action as a selector:
#selector(ViewController.onRegularClick)
XCode then complaints about:
Argument of #selector refers to a method that is not exposed to
Objective-C
So I have to set up the handler function with:
#objc func onRegularClick(sender: UIButton)
Can some one please put this noob on the right direction by guiding me to the documentation, or even give a short explanation, on:
why can't I no longer pass simply the function name String to the action?
how is the proper way to implement this following the Swift Way? Using the Selector class?
why do we need to pass the #objc keyword and how it affects the function?
Thank you!
why can't I no longer pass simply the function name String to the action?
Using strings for selectors has been deprecated, and you should now write #selector(methodName)instead of "methodName". If the methodName() method doesn't exist, you'll get a compile error – another whole class of bugs eliminated at compile time. This was not possible with strings.
how is the proper way to implement this following the Swift Way? Using the Selector class?
You did it the right way:
button.addTarget(self, action: #selector(ClassName.methodName(_:)), forControlEvents: UIControlEvents.TouchUpInside)
why do we need to pass the #objc keyword and how it affects the function?
In Swift the normal approach is to bind method's calls and method's bodies at compile time (like C and C++ do). Objective C does it at run time. So in Objective C you can do some things that are not possible in Swift - for example it is possible to exchange method's implementation at run time (it is called method swizzling). Cocoa was designed to work with Objective C approach and this is why you have to inform the compiler that your Swift method should be compiled in Objective-C-like style. If your class inherits NSObject it will be compiled ObjC-like style even without #objc keyword.
Well, it is called evolution
When there are some arguments in the method, you should declare the selector as:
let selector = #selector(YourClass.selector(_:))
You can type only #selector(selector(_:)) if the selector is in the same class of the caller. _: means that accept one parameter. So, if it accept more parameters, you should do something like: (_:, _:) and so on.
I found out that the #objc is needed only when the function is declared as private or the object doesn't inherit from NSObject
1: Currently you can, but it will create a deprecated warning. In Swift
3 this will be an error, so you should fix it soon. This is done
because just using a String can not be checked by the compiler if
the function really exists and if it is a valid Objective C function
which can be resolved dynamically during runtime.
2: Do it in this way:
button.addTarget(self, action: #selector(MyViewControllerClass.buttonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
3: Usually you not have to use the #objc attribute. I assume your class ViewController is (for any reason) not derived from UIViewController. If it derives from UIViewController is inherits also the needed ObjC behavior for calling selectors on functions.
For swift3.0 just do like below code :
yourButton.addTarget(self, action: #selector(yourButtonPressed), for: .touchUpInside)
and yourButtonPressed method
#IBAction func yourButtonPressed(sender:UIButton) {
// Do your code here
}
Everyones's answers are perfect but I have a better approach. Hope you gonna like it.
fileprivate extension Selector {
static let buttonTapped =
#selector(ViewController.buttonTapped(_:))
}
...
button.addTarget(self, action: .buttonTapped, for: .touchUpInside)
here in this file private will help to show buttonTapped only in file.
Programmatically
button.addTarget(self, action: #selector(returnAction), for: .touchUpInside)
// MARK: - Action
#objc private func returnAction(sender: UIButton) {
print(sender.tag)
}

Resources