How to pass parameters via the selector/action?

蓝咒 提交于 2019-12-06 05:51:33

问题


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

回答1:


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.




回答2:


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

According to the documentation using setTitle is the general way to set a title of a UIButton instance. So you're doing it right.



来源:https://stackoverflow.com/questions/11095648/how-to-pass-parameters-via-the-selector-action

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