Search code examples
rubymotion

RubyMotion and UIPickerView


I want to use UIPickerView to select a number and assign the selected number to a label. I worked out how to do it using the ib gem and using interface builder to create the initial interface and it works fine. However, I would like to do it purely using RubyMotion code and I can't for the life of me get it to work. The best I have managed is for the label to return True and not a number.

I'm using the following standard code for the picker view delegate methods:

def pickerView(pickerView, numberOfRowsInComponent:component)
  101
end

def pickerView(pickerView, titleForRow:row, forComponent:component)
  row.to_s
end

def numberOfComponentsInPickerView (pickerView)
  1
end

def pickerView(pickerView, didSelectRow:row, inComponent:component)

end

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

def submit
  totals.addTotals(myPicker.selectedRowInComponent(0))
end

and then the label text is populated like this:

numLabel = UILabel.new
numLabel.text = "Number Selected:  #{submit}"
numLabel.font = UIFont.boldSystemFontOfSize(18)
numLabel.frame = [[20,320],[260,340]]
numLabel.numberOfLines = 2
numLabel.adjustsFontSizeToFitWidth = 'YES'
self.view.addSubview numLabel

The totals is a shared client.


Solution

  • Here is how to do it in RubyMotion alone. Note that the label and picker are set up in viewDidLoad. The label gets updated in pickerView:didSelectRow:inComponent:

    app_delegate.rb

    class AppDelegate
      def application(application, didFinishLaunchingWithOptions:launchOptions)
        @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
        @window.rootViewController = PickerDemo.new
        @window.makeKeyAndVisible
        true
      end
    end
    

    picker_demo.rb

    class PickerDemo < UIViewController
      def viewDidLoad
        view.backgroundColor = UIColor.whiteColor
        @numLabel = UILabel.new
        @numLabel.text = "Number Selected:  0"
        @numLabel.font = UIFont.boldSystemFontOfSize(18)
        @numLabel.frame = [[20,100],[260,120]]
        @numLabel.numberOfLines = 2
        @numLabel.adjustsFontSizeToFitWidth = true
        view.addSubview(@numLabel)
    
        @picker = UIPickerView.new
        @picker.frame = [[0, 183], [320, 162]]
        @picker.delegate = self
        @picker.dataSource = self
        view.addSubview(@picker)
      end
    
      def pickerView(pickerView, numberOfRowsInComponent:component)
        101
      end
    
      def pickerView(pickerView, titleForRow:row, forComponent:component)
        row.to_s
      end
    
      def numberOfComponentsInPickerView(pickerView)
        1
      end
    
      def pickerView(pickerView, didSelectRow:row, inComponent:component)
        @numLabel.text = "Number Selected:  #{row}"
      end
    end