Azuki Digital

code ruby rubymotion ios formotion technical Aug 29, 2014

iOS Switch on change action

Luke profile image

Writen by Luke

header image for post of

rubymotion logo I’ve been using RubyMotion recently to build an iOS app for a client. It’s really good fun!
It turns out that there’s an easy way to perform actions, such as saving, when toggling a switch in RubyMotion. I’m using Formotion but the same approach should work without it.

There’s no on_change callback on the switch field so I had to find another solution. RubyMotion BubbleWrap’s Observers is the way I sorted it. You have to include the BW::KVO module which gives you the ‘observe’ function. This takes the object to observe, the param to observe and a callback block.

Something like this:

class SwitchOnChangeScreen < PM::FormotionScreen
  include BW::KVO

  def on_load
    sync_over_3g = self.form.sections[0].rows[0] # TODO change this, error prone
    observe(sync_over_3g, "value") do |old_val, val|
      # save new val
      App.alert(val ? "Yes" : "No")
    end
  end

  def table_data
    {
      sections: [{
        title: "Network",
        rows: [{
          title: "Sync over 3G",
          key: :sync_over_3g,
          type: :switch,
          value: false
        }]
      }]
    }
  end
end

The result:

switch on change preview