Search code examples
iosrubyrubymotion

Rubymotion: More generic way to set navigationBar properties


Is there a more generic way to set the navigationBar properties? I would like to set the translucent to false and an image as a title. What is strange for me is that I can set the tintColor and barTintColor in app_delegate.rb but not the other properties. It is a little weird to run this code in all my screens.

I am using the latest Rubymotion and I am using the promotion gem to build my screens.

class AppDelegate < ProMotion::Delegate
  include PM::Styling

  def on_load(app, options)
    set_appearance_defaults
  end

  def set_appearance_defaults
    UINavigationBar.appearance.tintColor = UIColor.whiteColor
    UINavigationBar.appearance.barTintColor = hex_color("3B4044")
  end

end

class LoginScreen < PM::Screen

  def on_init
    self.navigationItem.titleView = UIImageView.alloc.initWithImage(UIImage.imageNamed("logos/navigation_bar_logo.png"))
    self.navigationController.navigationBar.translucent = false
  end

end

Solution

  • Added some comments above, but here's an actual answer you can try out for yourself that's pretty flexible.

    # app/mk_screen.rb
    class MKScreen < PM::Screen
      def useLogoNavbar
        self.navigationItem.titleView = UIImageView.alloc.initWithImage(UIImage.imageNamed("logos/navigation_bar_logo.png"))
        self.navigationController.navigationBar.translucent = false
      end
    end
    
    # app/login_screen.rb
    class LoginScreen < MKScreen
      useLogoNavbar
    end
    

    Now you still have to call a method, but it at least gives you an option of whether to use it or not. It also means you can use MKScreen to place little common code in for your view controllers.