I am building an iOS app using Rubymotion. To be able to reuse code I have created a file called elements.rb (a module) where I got many functions which renders different stuff. All works perfectly fine.
This is one of the functions:
def create_nav_button (hash = {})
# Set the default values
defaultFont = UIFont.fontWithName('Avenir-Medium', size:13)
buttonNormal = UIImage.imageNamed('navbar/button.png')
buttonSelected = UIImage.imageNamed('navbar/button_selected.png')
# Create the button
button = UIBarButtonItem.alloc.init
button.title = hash[:title]
button.action = hash[:action] || 'open'
button.target = self
button.setBackgroundImage(buttonNormal, forState:UIControlStateNormal, barMetrics:UIBarMetricsDefault)
button.setBackgroundImage(buttonSelected, forState:UIControlStateHighlighted, barMetrics:UIBarMetricsDefault)
button.setTitleTextAttributes({UITextAttributeFont => defaultFont}, forState:UIControlStateNormal)
# Add button to navbar
if (hash[:position] == 'right')
self.navigationItem.rightBarButtonItem = button
else
self.navigationItem.leftBarButtonItem = button
end
end
This is how I call it in the controller file:
create_nav_button (:title => 'Info', :action => 'project_details', :position => 'right')
Is this a good way of reusing elements? How can I change the title of the button dynamically?
Thankful for all input!
That works. You’ll want to return the button at the end of your method:
Then call it like this:
I don’t know of an easy way you can change the title. You could always remove the button and re-add it with a new title.