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

Quotation Bank App | GCSE & A-Level English Revision

We’re excited to share that **The Quotation Bank App** — developed in partnership with *The Quotation Bank* — is now live on the **App Store and Google Play**.

Read more

Enabling Apple Pay within Stripe Connect accounts

How we used Stripe Connect in a SaaS product to manage platform payments, with practical implementation notes, tradeoffs, and lessons from delivery.

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.