4

別の関数を呼び出すときに 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

アップデート:

OK、これは機能するインスタンス変数を持つメソッドです。

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

2 に答える 2

7

UIButtonrubymotion呼び出しに「パラメータ」を付ける最も簡単な方法は、タグを使用することです。

最初に属性を持つボタンを設定し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

最初に、動作するアクションを設定しようとしましたが、メソッドaction: :buttonClickedを使用できませんでした。sender

于 2012-07-13T21:06:29.437 に答える
0

はい、通常は Controller クラスでインスタンス変数を作成し、任意のメソッドからメソッドを呼び出すだけです。

ドキュメントによると、使用setTitleUIButtonインスタンスのタイトルを設定する一般的な方法です。だからあなたはそれを正しくやっています。

于 2012-06-20T11:06:22.190 に答える