Skip to content

Instantly share code, notes, and snippets.

@neilberget
Created May 10, 2012 00:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilberget/2649989 to your computer and use it in GitHub Desktop.
Save neilberget/2649989 to your computer and use it in GitHub Desktop.
[EXPERIMENTAL] A ruby method that looks for all accessibility labels in all the xib files in the resources directory of a RubyMotion project, create auto-incrementing tags for those elements, and create a ruby file mapping constants named after the labels
# OPTIONAL: I'm not sure method_missing is ok in RubyMotion projects??
class UIView
def method_missing(meth, *args, &block)
if Kernel.const_defined? meth.upcase
viewWithTag(Kernel.const_get(meth.upcase))
else
super
end
end
end
task :labels do
require './xib_labels'
XibLabels.process
end
require 'nokogiri'
class XibLabels
def self.process
d = Dir.new("resources")
d.each { |entry|
next unless /xib$/.match entry
f = File.open("resources/#{entry}")
doc = Nokogiri::XML(f)
f.close
labelMap = {}
labels = doc.xpath("//string[@key='IBUIAccessibilityLabel']")
tagCounter = 1
labels.each { |label|
puts "Found: #{label.content}"
tag = label.xpath("../../int[@key='IBUITag']")[0]
if !tag
parent = label.xpath("../..")[0]
tag = Nokogiri::XML::Node.new "int", doc
tag['key'] = "IBUITag"
parent.add_child tag
end
tag.content = tagCounter
labelMap[label.content.upcase] = tagCounter
tagCounter += 1
}
File.open("resources/#{entry}",'w') {|f| doc.write_xml_to f}
labelsOutput = ""
labelMap.each { |k,v|
labelsOutput += "#{k} = #{v}\n"
}
File.open('app/label_tag_map.rb', 'w') {|f| f.write labelsOutput }
}
end
end
@neilberget
Copy link
Author

EXPERIMENTAL: Backup anything you try this on!!!!

This is a method of making xib files easier to work with in RubyMotion projects. To get started with using them, check out: http://ianp.org/2012/05/07/rubymotion-and-interface-builder/ but note that as of RubyMotion 1.3 the step involving ibtool is handled automatically by the RubyMotion compiler if the xib file is saved in the resources folder.

Where this gist comes in is that it will generate tags for every UI element that has an accessibility label written and give you a ruby constant that can be easily used to get a reference to those elements in your code (by running 'rake labels' )

So, instead of: view.viewWithTag(7) (where 7 might be the tag number you assigned to a view element) you can write view.viewWithTag(ADD_ENTRY_BUTTON) assuming you have a UIButton with an accessibility label of "add_entry_button"

Taking this a step further, (although not sure this is a real great idea) you could open the UIView class and add a method_missing for even easier access and get references to your elements with simply: view.add_entry_button

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment