Search code examples
objective-crubymotion

How to add a custom button to navbar?


I am creating a Rubymotion app and I need to create a custom button in the Navbar. I am running the code in the controller.

I am using this code:

button = UIBarButtonItem.alloc.init
    button.title = 'Add'
    button.style = UIBarButtonItemStylePlain
    button.target = self
    button.action = 'performAdd'
    button.setBackgroundImage(checkInImage, forState:UIControlStateNormal, forBarMetrics:UIBarMetricsDefault)
    button.setBackgroundImage(checkInPressed, forState:UIControlStateHighlighted, forBarMetrics:UIBarMetricsDefault)
    self.navigationItem.rightBarButtonItem = button

But I get this error when running rake:

Terminating app due to uncaught exception 'NoMethodError', reason: 'first_controller.rb:21:in `button': undefined method `setBackgroundImage' for #<UIBarButtonItem:0x6b3c1d0> (NoMethodError)

SOLUTION

    button = UIBarButtonItem.alloc.init
        button.title = 'Add'
        button.target = self
        button.action = 'performAdd'
        button.setBackgroundImage(checkInImage, forState:UIControlStateNormal, barMetrics:UIBarMetricsDefault)
        button.setBackgroundImage(checkInPressed, forState:UIControlStateHighlighted, barMetrics:UIBarMetricsDefault)
self.navigationItem.rightBarButtonItem = button

Solution

  • According to my reading, it's barMetrics, not forBarMetrics. So:

    setBackgroundImage(checkInImage,
                       forState:UIControlStateNormal, barMetrics:UIBarMetricsDefault)