2012-11-16 47 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

绝对的辉煌。感谢您花时间帮助我解决这个问题! –

相关问题