2013-12-10 37 views
0

繼茶杯Tweets example,我試圖訪問佈局塊Rubymotion茶杯變量的作用域

class WindowController < TeacupWindowController 
    stylesheet :pref_window 

layout do 

    @loginButton = subview(
    NSButton, :loginButton, 
    state: NSOffState, 
    buttonType: NSSwitchButton, 
    action: 'login', 
    target: self, 
    ) 

    puts @loginButton.class 

end 

puts @loginButton.class 

第一puts返回NSButton類之外的變量,但第二個返回無類。

如果我需要以編程方式更改它,我該如何訪問@loginButton?

例如:

@loginButton.setState(NSOnState) 

不佈局塊之外工作。

回答

1

您可以在WindowController使用attr_accessor,然後在佈局塊,您可以使用self.loginButton,它會在WindowController分配給您訪問按鈕。

我還假設第二個puts實際上是在另一種方法,這只是示例代碼。

class WindowController < TeacupWindowController 
    stylesheet :pref_window 
    attr_accessor :loginButton 

    layout do 

    self.loginButton = subview(
     NSButton, :loginButton, 
     state: NSOffState, 
     buttonType: NSSwitchButton, 
     action: 'login', 
     target: self, 
    ) 

    puts self.loginButton.class 

    end 

    puts self.loginButton.class 
end 
+0

感謝您的提示。在這個問題中,我鏈接的tweets例子中,他們不使用self。 – vash

+0

這是因爲它們僅在操作內部使用變量:與變量相關。所以我可以在我的'def login'中使用@loginButton變量,但不能在其他方法定義中使用。這是正確的嗎? – vash

+0

我想我可能已經得到了這個錯誤......你的問題可能只是佈局塊尚未被調用。如果你在動作中使用@loginButton或者在視圖加載和顯示後運行的其他東西,那麼一切都應該沒問題。 – FluffyJack