2012-11-16 52 views
0

我在寫一個Rubymotion應用程序,我想自定義TabBar。在NSScreencasts.com上,他們解釋瞭如何在Objective-C中完成它,但是如何將下面的代碼轉換成Ruby?如何將自定義背景圖像設置爲tabbar?

- (id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
     [self customize];   
    } 
    return self; 
} 

- (id)initWithCoder:(NSCoder *)aDecoder { 
    self = [super initWithCoder:aDecoder]; 
    if (self) { 
     [self customize]; 
    } 
    return self; 
} 

- (void)customize { 
    UIImage *tabbarBg = [UIImage imageNamed:@"tabbar-background.png"]; 
    UIImage *tabBarSelected = [UIImage imageNamed:@"tabbar-background-pressed.png"]; 
    [self setBackgroundImage:tabbarBg]; 
    [self setSelectionIndicatorImage:tabBarSelected]; 
} 

@end 

這是我的嘗試:

class CustomTabbar < UITabBarController 
    def init 
    super 
    customize 
    self 
    end 

    def customize 
    tabbarBg = UIImage.imageNamed('tabbar.jpeg') 
    self.setBackgroundImage = tabbarBg 
    end 
end 

但是,如果我運行它,我得到這個錯誤:

Terminating app due to uncaught exception 'NoMethodError', reason: 'custom_tabbar.rb:5:in `init': undefined method `setBackgroundImage=' for #<CustomTabbar:0x8e31a70> (NoMethodError) 

UPDATE

*這是我app_delete文件:*

class AppDelegate 
    def application(application, didFinishLaunchingWithOptions:launchOptions) 
    first_controller = FirstController.alloc.init 
    second_controller = SecondController.alloc.init 

    tabbar_controller = CustomTabbar.alloc.init 
    tabbar_controller.viewControllers = [first_controller, second_controller] 

    @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds) 
    @window.rootViewController = tabbar_controller 
    @window.makeKeyAndVisible 
    true 
    end 
end 
+0

你有沒有嘗試過'self.backgroundImage = tabbarBg'或'self.setBackgroundImage(tabbarBg)'? – kuba

+0

是的,都失敗了。 –

+0

另外我看到一個問題,你子類'UITabBarController'(這是一個控制器),但相反,你應該繼承'UITabBar'(這是一個UIView) – kuba

回答

1

據「聊天」我們有,在我看來,你是對的視圖和控制器適當的層次很困惑。控制器是擁有視圖的對象,但控制器沒有任何可視屬性。視圖具有視覺效果(如背景圖像)。所以例如當你有一個標籤欄時,你實際上有:1)TabBarController 2)TabBar(視圖)。

現在,TabBar是一個視圖,它有一個名爲「backgroundImage」的屬性,通過它可以更改背景。當然,TabBarController沒有這種東西,但它有一個「內部」控制器列表。

讓我告訴你一些你想要的代碼。它在Obj-C中,但應該直接將它重寫到Ruby中。我有這個在我的AppDelegate的didFinishLaunchingWithOptions方法:

UITabBarController *tbc = [[UITabBarController alloc] init]; 

UIViewController *v1 = [[UIViewController alloc] init]; 
UIViewController *v2 = [[UIViewController alloc] init]; 

tbc.viewControllers = @[v1, v2]; 
tbc.tabBar.backgroundImage = [UIImage imageNamed:@"a.png"]; 

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
self.window.rootViewController = tbc; 
self.window.backgroundColor = [UIColor whiteColor]; 
[self.window makeKeyAndVisible]; 
return YES; 

注意,該TabBarController有一個屬性「viewControllers」 - 這是內部控制器的列表。它還有一個屬性「tabBar」,它是對視圖UITabBar的引用。我訪問它並設置背景圖像。

+0

絕對的輝煌。感謝您花時間幫助我解決這個問題! –

相關問題