How to pass parameters through a selector / action?

Is there a way to pass parameters through addTarget call as it calls another function?

I also tried the sender method, but that breaks too. What is the correct way to pass parameters without creating global variables?

@my_button = UIButton.buttonWithType(UIButtonTypeRoundedRect) @my_button.frame = [[110,180],[100,37]] @my_button.setTitle("Press Me", forState:UIControlStateNormal) @my_button.setTitle("Impressive!", forState:UIControlStateHighlighted) # events newtext = "hello world" @my_button.addTarget(self, action:'buttonIsPressed(newtext)', forControlEvents:UIControlEventTouchDown) view.addSubview(@my_button) def buttonIsPressed (passText) message = "Button was pressed down - " + passText.to_s NSLog(message) end 

Update:

OK, here we use a method with an instance variable.

 @my_button = UIButton.buttonWithType(UIButtonTypeRoundedRect) @my_button.frame = [[110,180],[100,37]] @my_button.setTitle("Press Me", forState:UIControlStateNormal) @my_button.setTitle("Impressive!", forState:UIControlStateHighlighted) # events @newtext = "hello world" @my_button.addTarget(self, action:'buttonIsPressed', forControlEvents:UIControlEventTouchDown) view.addSubview(@my_button) def buttonIsPressed message = "Button was pressed down - " + @newtext NSLog(message) end 
+4
source share
2 answers

The easiest way to bind β€œparameters” to a rubimotion UIButton call is to use tags.

First configure the button with the tag attribute. This tag is the parameter that you want to pass to the target function.

 @button = UIButton.buttonWithType(UIButtonTypeRoundedRect) @button.setTitle "MyButton", forState:UIControlStateNormal @button.frame =[[0,0],[100,50]] @button.tag = 1 @button.addTarget(self, action: "buttonClicked:", forControlEvents:UIControlEventTouchUpInside) 

Now create a method that takes sender as a parameter:

 def buttonClicked(sender) mytag = sender.tag #Do Magical Stuff Here end 

Warning. As far as I know, the tag attribute accepts only integer values. You can get around this by putting your logic in the target function as follows:

 def buttonClicked(sender) mytag = sender.tag if mytag == 1 string = "Foo" else string = "Bar" end end 

First, I tried to set the action with action: :buttonClicked , which worked, but did not allow the use of the sender method.

+7
source

Yes, you usually create instance variables in your Controller class, and then just call methods on them using any method.

According to the documentation, using setTitle is a common way to set the header of an UIButton instance. So you are doing it right.

0
source

All Articles