将参数传递给swift中的#selector方法

时间:2016-07-12 12:30:22

标签: swift swift2 uitapgesturerecognizer

我想在单击图像时将多个参数传递给函数。 这是我的代码

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)

调用函数

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
        }

如何传递参数以便获得正确的值?

2 个答案:

答案 0 :(得分:4)

你做不到。来自文档:

  

手势识别器具有一个或多个与之关联的目标 - 动作对   ...
  调用的操作方法必须符合以下签名之一:

with open(filepath, "w") as fo:
    fo.writelines(','.join(map(str, x)) + '\n' for x in zip(AList,BList,InList))

您可以使用实例变量来传递参数。

答案 1 :(得分:2)

在swift2中,您无法在操作中传递参数。您可以只使用类属性:

Parallel.For(
            0,
            50000,
            new ParallelOptions
            {
                MaxDegreeOfParallelism = 10,
            },
            async (i) =>
            {
                var result = await client.ExecuteDistributedAsync(
                    (i % 2).ToString(),
                    TimeSpan.FromSeconds(5),
                    async () =>
                        {
                            await Task.Delay(500);
                            return $"Done: {i} [{(i % 2)}]";
                        });
                Console.WriteLine("--->" + (result ?? "TIMEOUT:" + i));
            });

调用函数

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)
}