Passing arguments to #selector method in swift [duplicate]

孤人 提交于 2019-12-21 16:44:28

问题


I want to pass multiple argument to a function while I click an image. Here is my code

var param1 = 120
var param2 = "hello"
var param3 =  "world"

let image: UIImage = UIImage(named: "imageName")!
 bgImage = UIImageView(image: image)

let singleTap = UITapGestureRecognizer(target: self, action:#selector(WelcomeViewController.tapDetected(_:secondParam:thirdParam:)))
singleTap.numberOfTapsRequired = 1
bgImage!.userInteractionEnabled = true
bgImage!.addGestureRecognizer(singleTap)

calling function

func tapDetected(firstParam: Int, secondParam: String, thirdParam: String) {
print("Single Tap on imageview")
            print(firstParam)  //print 120
            print(secondParam) // print hello
            print(thirdParam) /print world
        }

How can I pass arguments so that I can get correct values?


回答1:


You can't. From the documentation:

A gesture recognizer has one or more target-action pairs associated with it.
...
The action methods invoked must conform to one of the following signatures:

- (void)handleGesture;
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;

You may use instance variables to pass the parameters.




回答2:


In swift2 you can't pass parameters in actions. You may just use class properties:

var param1 = 120
var param2 = "hello"
var param3 = "world"
let image: UIImage = UIImage(named: "imageName")!
var bgImage: UIImageView?

override func viewDidLoad() {
    super.viewDidLoad()

    bgImage = UIImageView(image: image)
    let singleTap = UITapGestureRecognizer(target: self, action: #selector(WelcomeViewController.tapDetected))
    singleTap.numberOfTapsRequired = 1
    bgImage!.userInteractionEnabled = true
    bgImage!.addGestureRecognizer(singleTap)
}

calling function

func tapDetected() {
    print("Single Tap on imageview")
    print(param1) // print 120
    print(param2) // print hello
    print(param3) // print world
} 


来源:https://stackoverflow.com/questions/38328956/passing-arguments-to-selector-method-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!