2012-11-16 192 views
0

我正在創建一個Rubymotion應用程序,我需要在導航欄中創建一個自定義按鈕。 我在控制器中運行代碼。如何將自定義按鈕添加到導航欄?

我使用這個代碼:

button = UIBarButtonItem.alloc.init 
    button.title = 'Add' 
    button.style = UIBarButtonItemStylePlain 
    button.target = self 
    button.action = 'performAdd' 
    button.setBackgroundImage(checkInImage, forState:UIControlStateNormal, forBarMetrics:UIBarMetricsDefault) 
    button.setBackgroundImage(checkInPressed, forState:UIControlStateHighlighted, forBarMetrics:UIBarMetricsDefault) 
    self.navigationItem.rightBarButtonItem = button 

但運行時耙我得到這個錯誤:

Terminating app due to uncaught exception 'NoMethodError', reason: 'first_controller.rb:21:in `button': undefined method `setBackgroundImage' for #<UIBarButtonItem:0x6b3c1d0> (NoMethodError) 

SOLUTION

button = UIBarButtonItem.alloc.init 
     button.title = 'Add' 
     button.target = self 
     button.action = 'performAdd' 
     button.setBackgroundImage(checkInImage, forState:UIControlStateNormal, barMetrics:UIBarMetricsDefault) 
     button.setBackgroundImage(checkInPressed, forState:UIControlStateHighlighted, barMetrics:UIBarMetricsDefault) 
self.navigationItem.rightBarButtonItem = button 

回答

2

根據我的閱讀,這是barMetrics,不forBarMetrics。所以:

setBackgroundImage(checkInImage, 
        forState:UIControlStateNormal, barMetrics:UIBarMetricsDefault) 
+0

感謝編輯@dylan! –

+0

這工作得很好!謝謝! –

+0

順便說一句,RubyMotion剛剛發佈了API文檔,因此您可以在Ruby中看到正確的方法,而不必使用Apple的Obj-C參考:http://www.rubymotion.com/developer-center/api/UIBarButtonItem.html#了setBackgroundImage%3AforState%3AbarMetrics%3A-instance_method –

1

我真的是`RubyMotion新的,但仍然試圖幫助you.please原諒我,如果我不正確的任何地方。

編輯: 看到你的崩潰日誌Terminating app due to uncaught exception 'NoMethodError', reason: 'first_controller.rb:21:in按鈕「:未定義的方法setBackgroundImage' for #<UIBarButtonItem:0x6b3c1d0> (NoMethodError)。 我想,你不是在你的View controller中設置backgroundImage的正確方法,那就是爲什麼這樣的異常來了,我想是這樣。

而且我認爲確切原因可能是setBackgroundImage Method.I猜測是不正確的方法。應當backgroundImage。那麼你應該試試下面的代碼行中的ViewController

button.backgroundImage(checkInPressed, forState:UIControlStateHighlighted, forBarMetrics:UIBarMetricsDefault). 

這是您的代碼只是改變那一行。

button = UIBarButtonItem.alloc.init 
    button.title = 'Add' 
    button.style = UIBarButtonItemStylePlain 
    button.target = self 
    button.action = 'performAdd' 
    button.backgroundImage(checkInImage, forState:UIControlStateNormal, forBarMetrics:UIBarMetricsDefault) 
    button.backgroundImage(checkInPressed, forState:UIControlStateHighlighted, forBarMetrics:UIBarMetricsDefault) 
    self.navigationItem.rightBarButtonItem = button 

Here is The Link For The same You should take a View of this Link.

我希望你能得到一些想法..

+0

@NSPostWhenIdle對不起,我意識到我錯上再次way.sorry去同樣的事情...我要刪除或編輯。 – Kamarshad

+0

@NSPostWhenIdle謝謝,現在我正在尋找解決方案,以便我可以編輯我的答案... – Kamarshad

+0

謝謝!但是這也沒有幫助。 –