在按钮操作上传递参数:@selector [英] Passing parameters on button action:@selector

查看:131
本文介绍了在按钮操作上传递参数:@selector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将动态生成的按钮中的电影网址传递给MediaPlayer:

I want to pass the movie url from my dynamically generated button to MediaPlayer:

[button addTarget:self action:@selector(buttonPressed:) withObject:[speakers_mp4 objectAtIndex:[indexPath row]] forControlEvents:UIControlEventTouchUpInside];

操作:@selector()withObject:不起作用?

还有其他解决方案吗?

感谢您的帮助!

推荐答案

编辑。找到一种更简洁的方式!

按钮可以接收的一个参数是(id)sender 。这意味着您可以创建一个继承自UIButton的新按钮,该按钮允许您存储其他预期参数。希望这两个片段说明该怎么做。

One argument that the button can receive is (id)sender. This means you can create a new button, inheriting from UIButton, that allows you to store the other intended arguments. Hopefully these two snippets illustrate what to do.

  myOwnbutton.argOne = someValue
  [myOwnbutton addTarget:self action:@selector(buttonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];

- (IBAction) buttonTouchUpInside:(id)sender {
  MyOwnButton *buttonClicked = (MyOwnButton *)sender; 
  //do as you please with buttonClicked.argOne
}






这是我原来的建议。

有一种方法可以达到相同的效果,但不是漂亮。假设您要在导航方法中添加参数。下面的代码不允许您将该参数传递给导航

There is a way to achieve the same result, but it's not pretty. Suppose you want to add a parameter to your navigate method. The code below will not allow you to pass that parameter to navigate.

[button addTarget:self action:@selector(navigate) forControlEvents:UIControlEventTouchUpInside];

要解决此问题,您可以移动导航方法到它自己的类并将参数设置为该类的属性...

To get around this you can move the navigate method to a class of it's own and set the "parameters" as attributes of that class...

NavigationAid *navAid = [[NavigationAid alloc] init];
navAid.firstParam = someVariableOne
navAid.secondParam = someVariableTwo
[button addTarget:navAid action:@selector(navigate) forControlEvents:UIControlEventTouchUpInside];

当然,您可以将导航方法保留在原始类中并由navAid调用,只要因为它知道在哪里找到它。

Of course you can keep the navigate method in the original class and have it called by navAid, as long as it knows where to find it.

NavigationAid *navAid = [[NavigationAid alloc] init];
navAid.whereToCallNavigate = self
navAid.firstParam = someVariableOne
navAid.secondParam = someVariableTwo
[button addTarget:navAid action:@selector(navigate) forControlEvents:UIControlEventTouchUpInside];

就像我说的,它不漂亮,但它对我有用,我没有找到任何人建议任何其他有效的解决方案。

Like I said, it's not pretty, but it worked for me and I haven't found anyone suggesting any other working solution.

这篇关于在按钮操作上传递参数:@selector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆