2012-04-11 27 views
0

我有一個類tabBarController,每當它的selectedIndex屬性發生變化時,我想觸發一個自定義方法。我該如何做到這一點?如何觸發財產變更的方法?

這是怎麼tabBarController爲H的情況下被宣佈瓦爾:

BaseViewController *tabBarController; 

回答

5

使用UITabBar的-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item方法來確定的標籤,因此你要調用該方法的指數。

+0

詳情駕駛室在這裏找到。 http://developer.apple.com/library/ios/#documentation/uikit/reference/UITabBarDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITabBarDelegate – 2012-04-11 20:46:25

+0

這是否在m文件中爲類實現UITabBarControllerDelegate協議? – zakdances 2012-04-11 20:51:20

+0

是的,確切地說。 – CodaFi 2012-04-11 20:53:38

3

這是一個完美的鍵值觀察候選人。基本上,當數值發生變化時,通知會被觸發並被您定義的任何observers拾取,並且該通知將被視爲對任何更改進行觀察。當您建立自己和觀察員並實施observeValueForKeyPath:方法時,您可以使用任何方法啓動它。

這裏是一個很好的起點:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html#//apple_ref/doc/uid/10000177-BCICJDHA

有點令人生畏在第一,但基本上魔法使用得當。

編輯:沒有看到它很簡單UITabBarController。是的,只需使用委託方法即可。 KVO對此有點矯枉過正。

+0

一般而言,KVO非常棒,但如果有代表方法,則設置起來會更容易。 – benzado 2012-04-11 20:47:56

0

創建一個setter:

- (void)setSelectedIndex:(NSInteger*)integer 
{ 
    // Do stuff 
    selectedIndex=integer; 
    // Or: [super setSelectedIndex:integer]; 
} 
+0

我是否需要創建一個子類來使用此setter?它在哪裏? – zakdances 2012-04-11 21:13:39

0

使用delegate方法-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item