iOS Switch on change action

by Luke, Founder

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

More articles

Why engineering process is becoming a consultancy’s biggest advantage

As AI makes code faster to produce, the real differentiator for software consultancies is shifting to the engineering process around it.

Read more

Why mobile apps need ongoing support

Getting a mobile app into the App Store and Google Play is not the end of the story. Ongoing support keeps it compatible, reliable and store-ready as platforms change.

Read more
The Azuki team smiling and gathered together, ready to build and collaborate with clients.

Ready when you are

Let’s build something together

Whether you’re starting fresh or looking to improve things, we’re ready to talk.