How to pass variable to new method I call when using @selector(methodname)

血红的双手。 提交于 2019-11-29 17:56:43
ehope

If you just have to pass an integer associated to each disclosurebutton, you can set disclosurebutton.tag = integer value;.

Sort of hacky to pass data around in tags but in simple cases it works.

Also for this to work, declare loadpano this way:

- (void)loadPano:(UIButton*)sender
{
    NSInteger relevantInteger = sender.tag;
   // More code here
}

And set the target like this:

[disclosureButton addTarget:self 
                     action:@selector(loadPano:) 
           forControlEvents:UIControlEventTouchUpInside];    

Note that the method now takes a parameter so the selector includes a colon.

There are several solutions:

  1. Use the tag. But this can only be an integer.
  2. Add an instance variable (probably accessed using a property) to the class of the button. That means you must make a custom class for the button.
  3. Most general: Use associated objects (a.k.a. associative references), using the runtime functions objc_setAssociatedObject() and objc_getAssociatedObject()

You can not pass values other than sender and eventType in target-action methods.

The action message may optionally include the sender and the event as parameters, in that order.

If that integerVariable is a constant, then you can set it as a tag for the control from which you are initiating that action (in your case it is disclosureButton).

or

You can take an instance variable in your class, and access that value in loadPano method.

In the general case, you can create an instance of NSInvocation with your target, selector, and whatever parameters it needs. Then you call the invocation's -invoke method to send the message to the target.

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