Problem
centerLabelGesture is being defined outside of the scope of viewDidLoad(), so at the time that .addGestureRecognizer(centerLabelGesture) is called, centerLabelGesture is not defined yet.
import UIKit
import SnapKit
class ViewController: UIViewController {
var screen: UIView!
var centerLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
screen = UIView()
centerLabel = UILabel()
view.addSubview(screen)
screen.addSubview(centerLabel)
screen.backgroundColor = .white
screen.snp.makeConstraints { (make) in
make.top.equalTo(view)
make.right.equalTo(view)
make.left.equalTo(view)
make.bottom.equalTo(view)
}
centerLabel.text = "I hope I'm centered."
centerLabel.snp.makeConstraints { (make) in
make.center.equalTo(screen)
}
centerLabel.isUserInteractionEnabled = true
centerLabel.addGestureRecognizer(centerLabelGesture)
}
let centerLabelGesture = UITapGestureRecognizer(target: self, action: #selector(centerLabelTapped))
#objc func centerLabelTapped() {
centerLabel.text = "Ouch, you tapped me!"
}
}
Update 1/19/2019
matt pointed out that centerLabelGesture needs to be declared prior to centerLabel.addGestureRecognizer(centerLabelGesture), inside viewDidLoad()
This is a subtle mistake. The problem is the place you've put this line:
let centerLabelGesture = UITapGestureRecognizer(target: self, action: #selector(centerLabelTapped))
Move that line into the viewDidLoad code:
centerLabel.isUserInteractionEnabled = true
let centerLabelGesture = UITapGestureRecognizer(target: self, action: #selector(centerLabelTapped))
centerLabel.addGestureRecognizer(centerLabelGesture)
The reason is that where you've got that line, it's an instance property, and when you say self as the target in an instance property initializer, it doesn't mean what you think it does (it means the class, not the instance), so the message when you tap is misdirected and does nothing.
I have filed a bug on this issue; in my opinion the compiler should at least warn you that you're making a potential mistake.
Try adding this line in viewDidLoad
centerLabelGesture.numberOfTapsRequired = 1
Argument of '#selector' does not refer to an '#objc' method, property,
or initializer
Problem : Above Error when i try to pass argument with selector
code snippet:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(labelPressed(i: 1)))
func labelPressed(i: Int){
print(i)
}
You cannot pass a parameter to a function like that. Actions - which this is, only pass the sender, which in this case is the gesture recognizer. What you want to do is get the UIView you attached the gesture to:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(labelPressed())
func labelPressed(_ recognizer:UITapGestureRecognizer){
let viewTapped = recognizer.view
}
A few more notes:
(1) You may only attach a single view to a recognizer.
(2) You might want to use both the `tag` property along with the `hitTest()` method to know which subview was hit. For example:
let view1 = UIView()
let view2 = UIView()
// add code to place things, probably using auto layout
view1.tag = 1
view2.tag = 2
mainView.addSubview(view1)
mainView.addSubview(view2)
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(mainViewTapped())
func mainViewTapped(_ recognizer:UITapGestureRecognizer){
// get the CGPoint of the tap
let p = recognizer.location(in: self)
let viewTapped:UIView!
// there are many (better) ways to do this, but this works
for view in self.subviews as [UIView] {
if view.layer.hitTest(p) != nil {
viewTapped = view
}
}
// if viewTapped != nil, you have your subview
}
You just should declare function like this:
#objc func labelPressed(i: Int){ print(i) }
Update for Swift 3:
Using more modern syntax, you could declare your function like this:
#objc func labelTicked(withSender sender: AnyObject) {
and initialize your gesture recognizer like this, using #selector:
UITapGestureRecognizer(target: self, action: #selector(labelTicked(withSender:)))
Below is the code I have been using to try and add a gesture recogniser to something. I am getting the yellow error: "No method declared with objective C selector dragging" and then the program is crashing when I go to pan on it. The code and way of using a selector seems to work in all tutorials but it's the problem here.
class GameViewController: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let p = UIPanGestureRecognizer(target: self, action: #selector("dragging"))
p.delegate = self
characterGridView!.addGestureRecognizer(p)
}
func dragging(p: UIPanGestureRecognizer) {
print("works")
}
Your selector is incorrect.
Change
let p = UIPanGestureRecognizer(target: self, action: #selector("dragging"))
to
let p = UIPanGestureRecognizer(target: self, action: #selector(dragging(p:)))
I want to make a selector argument of my method refer to a closure property, both of them exist in the same scope. For example,
func backgroundChange() {
self.view.backgroundColor = UIColor.blackColor()
self.view.alpha = 0.55
let backToOriginalBackground = {
self.view.backgroundColor = UIColor.whiteColor()
self.view.alpha = 1.0
}
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(backToOriginalBackground), userInfo: nil, repeats: false)
}
However, this shows an error: Argument of #selector cannot refer to a property.
Of course I can define a new, separate method and move the implementation of the closure to it, but I want to keep it frugal for such a small implementation.
Is it possible to set a closure to #selector argument?
Not directly, but some workarounds are possible. Take a look at the following example.
/// Target-Action helper.
final class Action: NSObject {
private let _action: () -> ()
init(action: #escaping () -> ()) {
_action = action
super.init()
}
#objc func action() {
_action()
}
}
let action1 = Action { print("action1 triggered") }
let button = UIButton()
button.addTarget(action1, action: #selector(action1.action), forControlEvents: .TouchUpInside)
I tried this for UIBarButtonItem at least:
private var actionKey: Void?
extension UIBarButtonItem {
private var _action: () -> () {
get {
return objc_getAssociatedObject(self, &actionKey) as! () -> ()
}
set {
objc_setAssociatedObject(self, &actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
convenience init(title: String?, style: UIBarButtonItemStyle, action: #escaping () -> ()) {
self.init(title: title, style: style, target: nil, action: #selector(pressed))
self.target = self
self._action = action
}
#objc private func pressed(sender: UIBarButtonItem) {
_action()
}
}
Then you can do this:
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Test", style: .plain, action: {
print("Hello World!")
})
As #gnasher729 notes, this is not possible because selectors are just names of methods, not methods themselves. In the general case, I'd use dispatch_after here, but in this particular case, the better tool IMO is UIView.animateWithDuration, because it's exactly what that function is for, and it's very easy to tweak the transition:
UIView.animateWithDuration(0, delay: 0.5, options: [], animations: {
self.view.backgroundColor = UIColor.whiteColor()
self.view.alpha = 1.0
}, completion: nil)
It is now possible. I've created a gist for block-based selectors in Swift 4.
https://gist.github.com/cprovatas/98ff940140c8744c4d1f3bcce7ba4543
Usage:
UIButton().addTarget(Selector, action: Selector { debugPrint("my code here") }, for: .touchUpInside)`
You can use ActionClosurable which support UIControl, UIButton, UIRefreshControl, UIGestureRecognizer and UIBarButtonItem.
https://github.com/takasek/ActionClosurable
Bellow show example of UIBarButtonItem
// UIBarButtonItem
let barButtonItem = UIBarButtonItem(title: "title", style: .plain) { _ in
print("barButtonItem title")
}
#werediver's answer is excellent. Here's an update that allows you to call it as a function.
import Foundation
public extension Selector {
/// Wraps a closure in a `Selector`.
/// - Note: Callable as a function.
final class Perform: NSObject {
public init(_ perform: #escaping () -> Void) {
self.perform = perform
super.init()
}
private let perform: () -> Void
}
}
//MARK: public
public extension Selector.Perform {
#objc func callAsFunction() { perform() }
var selector: Selector { #selector(callAsFunction) }
}
You need to manage strong references to Selector.Performs. One way to do that is to subclass UIKit classes that were designed to work with target-action:
/// A `UITapGestureRecognizer` that wraps a closure.
public final class TapGestureRecognizer: UITapGestureRecognizer {
public init(_ perform: #escaping () -> Void) {
self.perform = .init(perform)
super.init(target: self.perform, action: self.perform.selector)
}
public let perform: Selector.Perform
}
let tapRecognizer = TapGestureRecognizer { print("🍔🐈") }
tapRecognizer.perform() // "🍔🐈"
No, #selector refers to an Objective-C method.
You can do something much better though: Add an extension to NSTimer that lets you create a scheduled timer not with a target and selector, but with a closure.
If you change the scope of block to a class scope rather than function and hold a reference to closure there.
You could invoke that closure with a function. in the class. So that way you can invoke that closure as a selector.
Something like this:
class Test: NSObject {
let backToOriginalBackground = {
}
func backgroundChange() {
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(test), userInfo: nil, repeats: false)
}
func test() {
self.backToOriginalBackground()
}
}
My solution was to create a class block variable like:
let completionBlock: () -> () = nil
Create a method which calls this completionBlock:
func completed(){
self.completionBlock!()
}
And inside where I want to put my selector like a block I did:
func myFunc(){
self.completionBlock = {//what I want to be done}
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(Myclass.completed), userInfo: nil, repeats: false)
}
So my answer to having a selector be assigned to a closure in a swift like manner is similar to some of the answers already, but I thought I would share a real life example of how I did it within a UIViewController extension.
fileprivate class BarButtonItem: UIBarButtonItem {
var actionCallback: ( () -> Void )?
func buttonAction() {
actionCallback?()
}
}
fileprivate extension Selector {
static let onBarButtonAction = #selector(BarButtonItem.buttonAction)
}
extension UIViewController {
func createBarButtonItem(title: String, action: #escaping () -> Void ) -> UIBarButtonItem {
let button = BarButtonItem(title: title, style: .plain, target nil, action: nil)
button.actionCallback = action
button.action = .onBarButtonAction
return button
}
}
// Example where button is inside a method of a UIViewController
// and added to the navigationItem of the UINavigationController
let button = createBarButtonItem(title: "Done"){
print("Do something when done")
}
navigationItem.setLeftbarButtonItems([button], animated: false)
Swift 5.2.x
First of all, you need to declare an "easy to use" typealias for your block:
typealias Completion = () -> ()
Then, you must declare private var to use "as a gate" for your function:
private var action: Completion?
After that, you should create a function that can be called by your Selector (it accept only string format) and to call private completion:
#objc func didAction() {
self.action?()
}
Finally you can re-write your function (using the new swift syntax) like:
Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(didAction), userInfo: nil, repeats: false)
self.action = backToOriginalBackground
P.S.: Remember that your variable (or parameter if you embed it to a function) must be of the same of type declared to your typeAlias so, in our case:
var backToOriginalBackground: () -> ()
or also:
var backToOriginalBackground: Completion
It has been several years since this question was asked, and it is worth noting that in those years, Apple has added variants of many selector-using methods that take closures instead.
The original question asks about NSTimer.scheduledTimerWithTimeInterval. That method is now spelled Timer.scheduledTimer and has a version that takes a closure. So the function in the original question can be rewritten thus:
extension UIViewController {
func changeBackground() {
self.view.backgroundColor = .black
self.view.alpha = 0.55
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in
self.view.backgroundColor = .white
self.view.alpha = 1.0
}
}
}
Here are some other common cases where, as of May 2016, a selector was required, but which can now use a closure:
UIControl now has an addAction method that takes a UIAction, and UIAction takes a closure. Subclasses of UIControl include UIButton, UISwitch, and UITextField.
UIBarButtonItem has an initializer that takes a UIAction.
NotificationCenter now has an addObserver method that takes a closure. It also supports Combine (the publisher method) and async/await (the notifications method).
RunLoop now has a perform method that takes a closure.
I am making an app with a variable amount of views all with a TapGestureRecognizer. When the view is pressed, i currently am doing this
func addView(headline: String) {
// ...
let theHeadline = headline
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
// ....
}
but in my function "handleTap", i want to give it an additional parameter (rather than just the sender) like so
func handleTap(sender: UITapGestureRecognizer? = nil, headline: String) {
}
How do i send the specific headline (which is unique to every view) as an argument to the handleTap-function?
Instead of creating a generic UITapGestureRecognizer, subclass it and add a property for the headline:
class MyTapGestureRecognizer: UITapGestureRecognizer {
var headline: String?
}
Then use that instead:
override func viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = MyTapGestureRecognizer(target: self, action: "tapped:")
gestureRecognizer.headline = "Kilroy was here."
view1.addGestureRecognizer(gestureRecognizer)
}
func tapped(gestureRecognizer: MyTapGestureRecognizer) {
if let headline = gestureRecognizer.headline {
// Do fun stuff.
}
}
I tried this. It worked great.