Is there a way to pass parameters via the addTarget call as it calls another function?
I've also tried the sender method - but that seems to break as well. What's the correct way to pass the 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's a method with an instance variable that worked.
@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
The easiest way of attaching "parameters" to a rubymotion UIButton
call is through the use of tags.
First set up a button with a tag
attribute. This tag is the parameter 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 accepts sender
as a parameter:
def buttonClicked(sender)
mytag = sender.tag
#Do Magical Stuff Here
end
Forewarning: As far as I know, the tag attribute only accepts integer values. You could get around this by putting your logic into the target function like this:
def buttonClicked(sender)
mytag = sender.tag
if mytag == 1
string = "Foo"
else
string = "Bar"
end
end
Initially I tried setting the action with action: :buttonClicked
which worked but did not allow for using the sender
method.