有没有办法通过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
"参数"附加到 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
预告:据我所知,标签属性只接受整数值。 您可以通过将逻辑放入目标函数中来解决此问题,如下所示:
def buttonClicked(sender)
mytag = sender.tag
if mytag == 1
string = "Foo"
else
string = "Bar"
end
end
最初,我尝试使用有效但不允许使用 sender
方法的action: :buttonClicked
设置操作。
是的,您通常在控制器类中创建实例变量,然后从任何方法调用它们的方法。
根据文档,使用 setTitle
是设置 UIButton
实例标题的通用方法。所以你做对了。