Skip to content

Add a 'done' button above the picker

tomtempest edited this page Apr 19, 2013 · 6 revisions

Allows the user to pick a value, then close the picker with a click on "done".

Based on http://bencoffman.com/blog/2012/04/07/iOSWantAButtonAboveAUIPickerOrKeyboardInputViewInputAccessoryView.aspx

module Formotion
  module RowType
    class PickerWithDoneRow < PickerRow
      include RowType::ItemsMapper

      def after_build(cell)
        super
        keyboardDoneButtonView             = UIToolbar.new
        keyboardDoneButtonView.barStyle    = UIBarStyleBlack
        keyboardDoneButtonView.translucent = true
        keyboardDoneButtonView.tintColor   = nil
        keyboardDoneButtonView.sizeToFit
 
        doneButton = UIBarButtonItem.alloc.initWithTitle("Done", style:UIBarButtonItemStyleDone,  target:self, action: 'picker_done_clicked')
        spacer1    = UIBarButtonItem.alloc.initWithBarButtonSystemItem(UIBarButtonSystemItemFlexibleSpace, target:self, action: nil)
        spacer     = UIBarButtonItem.alloc.initWithBarButtonSystemItem(UIBarButtonSystemItemFlexibleSpace, target:self, action: nil)
        keyboardDoneButtonView.setItems([spacer, spacer1, doneButton])
 
        row.text_field.inputAccessoryView = keyboardDoneButtonView
      end
 
      def picker_done_clicked
        # 'jump' to next input field if one exists
        if row.next_row && row.next_row.text_field
          row.next_row.text_field.becomeFirstResponder
        else
          # just hide the keyboard...
          row.text_field.resignFirstResponder
        end
      end
    end
  end
end 
 FORM = {
    sections: [
      {
        title: "Create a new Server",
        rows: [
          {
            title: 'Size',
            key: 'size',
            type: :picker_with_done,
            items: [ '512MB', '1GB', '2GB' ],
            placeholder: 'Server Size'
          },
    ...