Search code examples
rubymotion

Time picker using UIPickerView/UIDatePicker


I am trying to wrap my head around UIPickerView and how to use it to make a time picker. I found that UIDatePicker has time mode, but that's a component, not a view class. But I am not sure how to make a complex PickerView instead of some strings. Here what I have so far:

class NewAlarmViewController < UIViewController
  def viewDidLoad
    super

    self.title = "Add Alarm"
  end

  def loadView
    self.view = NewAlarmView.new

    self.view.showsSelectionIndicator = true
    self.view.dataSource = self
    self.view.delegate = self
  end

  # Necessary to implement these methods in order to be a datasource
  # - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
  def numberOfComponentsInPickerView pickerView
    2
  end

  # - (NSInteger)pickerView:(UIPickerView *)pickerView
  # numberOfRowsInComponent:(NSInteger)component;
  def pickerView(pickerView, numberOfRowsInComponent:component)
    24
  end

  def pickerView(pickerView, titleForRow:row, forComponent:component)
    "#{row}"
  end

  private

    def create_new_alarm(attributes)
      Alarm.create(attributes)
      Alarm.save
    end
end

And my view here. I have DatePicker commented out as it just sits on top of the picker, which is obviously not what I want. I don't see how to use DatePicker inside/instead of pickerView(pickerView, titleForRow:row, forComponent:component)

class NewAlarmView < UIPickerView
  # attr_accessor :button

  def init
    super

    self.backgroundColor = UIColor.whiteColor

    # date_picker = UIDatePicker.new
    # date_picker.frame = [[0, 150], [200, 500]]
    # date_picker.datePickerMode = UIDatePickerModeTime
    # addSubview(date_picker)

    self
  end
end

Solution

  • I've decided to approach it differently, instead to use TableView and with DatePicker as a component. There is a tableHeaderView method for UITableView, where I put the picker. That way I don't even need to use Autolayout. Hope that helps someone in the future.

    Here's the view itself:

    class NewAlarmView < UITableView
      attr_accessor :date_picker
    
      def initWithFrame(frame, style:style)
        super
    
        self.backgroundColor = UIColor.whiteColor
        self.scrollEnabled = false
    
        @date_picker                = UIDatePicker.new
        @date_picker.datePickerMode = UIDatePickerModeTime
        self.tableHeaderView        = @date_picker
    
        self
      end
    end