如何通过选择器/动作传递参数?

时间:2012-06-19 06:39:45

标签: rubymotion

有没有办法通过addTarget调用传递参数,因为它调用另一个函数?

我也尝试了发送方法 - 但这似乎也破了。在不创建全局变量的情况下传递参数的正确方法是什么?

@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

更新:

好的,这是一个有效的实例变量的方法。

@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

2 个答案:

答案 0 :(得分:7)

将“参数”附加到rubymotion UIButton调用的最简单方法是使用标记。

首先设置一个具有tag属性的按钮。此标记是您​​要传递给目标函数的参数。

@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)

现在创建一个接受sender作为参数的方法:

def buttonClicked(sender)
    mytag = sender.tag

   #Do Magical Stuff Here
end

预警:据我所知,tag属性只接受整数值。您可以通过将逻辑放入目标函数来解决这个问题:

def buttonClicked(sender)
    mytag = sender.tag

    if mytag == 1
      string = "Foo"

    else
      string = "Bar"
    end

end

最初,我尝试使用action: :buttonClicked设置操作,该操作有效,但不允许使用sender方法。

答案 1 :(得分:0)

是的,您通常在Controller类中创建实例变量,然后从任何方法调用它们的方法。

根据documentation使用setTitle是设置UIButton实例标题的一般方法。所以你做得对。

相关问题