How to pass parameters via the selector/action?

佐手、 提交于 2019-12-04 09:59:19

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.

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.

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