2012-06-19 44 views
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 

回答

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 

預警:據我所知,標籤屬性只接受整數值。你可以解決這個問題把你的邏輯到目標函數是這樣的:

def buttonClicked(sender) 
    mytag = sender.tag 

    if mytag == 1 
     string = "Foo" 

    else 
     string = "Bar" 
    end 

end 

起初,我試着設置與action: :buttonClicked其工作,但不允許使用sender方法的動作。

0

是的,你通常在你的Controller類中創建實例變量,然後從任何方法調用它們的方法。

根據documentation使用setTitle是設置UIButton實例標題的一般方法。所以你做對了。