如何将自定义背景图像设置为tabbar?

时间:2012-11-16 09:22:23

标签: objective-c rubymotion

我正在写一个Rubymotion应用程序,我想自定义TabBar。在NSScreencasts.com上,他们解释了如何在Objective-C中完成它,但是如何将下面的代码转换为Ruby?

- (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)

更新

*这是我的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

1 个答案:

答案 0 :(得分:1)

根据我们的“聊天”,在我看来,你对视图和控制器的正确层次非常困惑。控制器是拥有视图的对象,但控制器没有任何可视属性。视图具有视觉效果(如背景图像)。所以例如a当你有一个标签栏时,你实际上有: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的引用。我访问它并设置背景图像。