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)
}
Related
I work in a project were I came across multiples cases like this,
class ViewController: UIViewController {
private let clearCacheButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitle(AppMessages.General.Action.clearCache.description, for: .normal)
button.addTarget(self, action: #selector(clearCache), for: .touchUpInside)
return button
}()
}
self is being captured to add target for button, yet compiler does not complain about capturing self before initialisation, it works even without lazy var modifier...
Why is that?
Is this just a little convenience added by Apple at some point?
If I remember well it was not possible in the past
Thank you for the replies
The compiler has never complained about this. But it should (and I have filed a bug on this point), because the code you've written won't work: the button will not actually do anything when tapped. (The app might even crash, but then again it might not.)
The reason (for both phenomena) is that the compiler misinterprets the term self here to mean the class — which does exist before initialization of the instance.
The solution is to replace let by lazy var. That does work, because now the code will not actually be called until some later, when the instance does exist.
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
I'm trying to convert my project's source code from Swift 3 to Swift 4. One warning Xcode is giving me is about my selectors.
For instance, I add a target to a button using a regular selector like this:
button.addTarget(self, action: #selector(self.myAction), for: .touchUpInside)
This is the warning it shows:
Argument of '#selector' refers to instance method 'myAction()' in 'ViewController' that depends on '#objc' attribute inference deprecated in Swift 4
Add '#objc' to expose this instance method to Objective-C
Now, hitting Fix on the error message does this to my function:
// before
func myAction() { /* ... */ }
// after
#objc func myAction() { /* ... */ }
I don't really want to rename all of my functions to include the #objc mark and I'm assuming that's not necessary.
How do I rewrite the selector to deal with the deprecation?
Related question:
The use of Swift 3 #objc inference in Swift 4 mode is deprecated?
The fix-it is correct – there's nothing about the selector you can change in order to make the method it refers to exposed to Objective-C.
The whole reason for this warning in the first place is the result of SE-0160. Prior to Swift 4, internal or higher Objective-C compatible members of NSObject inheriting classes were inferred to be #objc and therefore exposed to Objective-C, therefore allowing them to be called using selectors (as the Obj-C runtime is required in order to lookup the method implementation for a given selector).
However in Swift 4, this is no longer the case. Only very specific declarations are now inferred to be #objc, for example, overrides of #objc methods, implementations of #objc protocol requirements and declarations with attributes that imply #objc, such as #IBOutlet.
The motivation behind this, as detailed in the above linked proposal, is firstly to prevent method overloads in NSObject inheriting classes from colliding with each other due to having identical selectors. Secondly, it helps reduce the binary size by not having to generate thunks for members that don't need to be exposed to Obj-C, and thirdly improves the speed of dynamic linking.
If you want to expose a member to Obj-C, you need to mark it as #objc, for example:
class ViewController: UIViewController {
#IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(foo), for: .touchUpInside)
}
#objc func foo() {
// ...
}
}
(the migrator should do this automatically for you with selectors when running with the "minimise inference" option selected)
To expose a group of members to Obj-C, you can use an #objc extension:
#objc extension ViewController {
// both exposed to Obj-C
func foo() {}
func bar() {}
}
This will expose all the members defined in it to Obj-C, and give an error on any members that cannot be exposed to Obj-C (unless explicitly marked as #nonobjc).
If you have a class where you need all Obj-C compatible members to be exposed to Obj-C, you can mark the class as #objcMembers:
#objcMembers
class ViewController: UIViewController {
// ...
}
Now, all members that can be inferred to be #objc will be. However, I wouldn't advise doing this unless you really need all members exposed to Obj-C, given the above mentioned downsides of having members unnecessarily exposed.
As Apple Official Documentation. you need to use #objc to call your Selector Method.
In Objective-C, a selector is a type that refers to the name of an
Objective-C method. In Swift, Objective-C selectors are represented by
the Selector structure, and can be constructed using the #selector
expression. To create a selector for a method that can be called from
Objective-C, pass the name of the method, such as
#selector(MyViewController.tappedButton(sender:)). To construct a selector for a property’s Objective-C getter or setter method, pass
the property name prefixed by the getter: or setter: label, such as
#selector(getter: MyViewController.myButton).
As of, I think Swift 4.2, all you need to do is assign #IBAction to your method and avoid the #objc annotation.
let tap = UITapGestureRecognizer(target: self, action: #selector(self.cancel))
#IBAction func cancel()
{
self.dismiss(animated: true, completion: nil)
}
As already mentioned in other answers, there is no way to avoid the #objc annotation for selectors.
But warning mentioned in the OP can be silenced by taking following steps:
Go to Build Settings
Search for keyword #objc
Set the value of Swift 3 #objc interface to Off
below is the screenshot that illustrates the above mentioned steps:
Hope this helps
If you need objective c members in your view controller just add #objcMembers at the top of the view controller. And you can avoid this by adding IBAction in your code.
#IBAction func buttonAction() {
}
Make sure to connect this outlet in storyboard.
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.
Up until now I have had this code
if UIScreen.instancesRespondToSelector(Selector("scale")) {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale);
}else{...}
I didn't write this code, so I'm not sure what it's for, but it looks like they wanted to verify that UIScreen.mainScreen() in fact can have the variable .scale(?).
When looking at the .scale, it looks to me like this has been available since iOS 4.0. Since we support down to iOS 7, this shouldn't be necessary, right?
Anyway, this is not the current problem.
I am now having hundreds of warnings due to Xcode 7.3 towards Swift 3 with these new selector-instantiations or whatnot.
Xcode wants me to change this:
Selector("scale")
into
#selector(NSDecimalNumberBehaviors.scale)
Until now, all other selectors I have changed have been logical, like "change Selector("hello") into #selector(MyClass.hello), but this NSDecimal.. sounds a bit drastic. Can I trust Xcode to pick the right selector? I can't find NSDecimalNumberBehaviors anywhere connected to UIScreen.scale.. If I type #selector(UIScreen.scale) I get an error..
The only thing I know for sure is that if I CMD+click scale here: NSDecimalNumberBehaviors.scale and here: UIScreen.mainScreen().scale I end up in different places..
As noted in comments, this code is a vestigial remnant of attempts to support old iOS versions that not only are no longer relevant, but can't even be targeted when developing in Swift.
Just call UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale) directly — the scale property exists on all iOS versions that you can target with Swift, so there's no need to check for it.
In fact, in general it's not a good idea to test for API availability using selector checks. A selector may exist on a version below the one you're targeting, but be private API with different behavior — so your check will succeed, but your code will not behave correctly. This is why the #available and #available system was introduced in Swift 2.
(Another upside of version-based availability checking: when an OS version gets old enough for you to drop support, it's much easier to find all the sites in your code that you can clean up. You don't have to remember which version which method/property became universal in.)
If for some other reason you need to form a Selector for UIScreen.scale... you can't use the #selector expression to do that in Swift 2.2, because scale is a property, not a method. In Swift 2.2, #selector takes a function/reference, and there's no way to get a reference to the underlying getter or setter method of a property. You'd still need to construct that selector from a string. To get around the warning, stash the string literal in a temporary:
let scale = "scale"
let selector = Selector(scale)
Or do some other dance that passes a string, but doesn't directly pass a string literal, to the Selector initializer:
let selector = Selector({"scale"}())
In Swift 3 there'll be a special form of #selector for property getters/setters, but it hasn't landed yet.
my two cents:
1) swift has a new sntax for selectors
2) compiler can safely detect methods based on:
n. of params
type of every param
result type (ONLY in pure swift, so let's forget it now)
let see 4 cases:
A)
..
closeBtn.addTarget(self, action: #selector(doIt), for: .touchUpInside)
}
func doIt(_ sender: UIButton) {
print("touched")
}
func doIt() {
print("touched2 ")
}
Ambiguous use of 'doIt'
B)
closeBtn.addTarget(self, action: #selector(doIt), for: .touchUpInside)
}
// func doIt(_ sender: UIButton) {
// print("touched")
// }
func doIt() {
print("touched2 ")
}
it works, as compiler is able to detect the ONLY method that
can match the signature
C)
closeBtn.addTarget(self, action: #selector(doIt(_:)), for: .touchUpInside)
}
func doIt(_ sender: UIButton) {
print("touched")
}
func doIt() {
print("touched2 ")
}
it works, as compiler is able to detect the ONLY method that
can match the signature.
D)
closeBtn.addTarget(self, action: #selector(doIt), for: .touchUpInside)
}
func doIt(_ sender: UIButton) {
print("touched")
}
/*
func doIt() {
print("touched2 ")
}
*/
it works and:
compiler is able to detect the ONLY method that can match the
signature
in debugger You will get the correct button reference too, as the
UIButton CODE (in iOS libs) pushes the button address on the
stack, as compiler does create a stack frame.