Tag Archives: picker view

This Old App: Why I Hate PickerViews, but Learned To Love Them.

A few months ago, Apple removed my app Interval RunCalc from the App Store for being too old. In this series of articles I’ll document what I did on rebuilding and improving the app. In the last installment, I placed my new model into the old app, fixed a lot of errors from taking 2013 Objective-C code in 2017’s Xcode and make a quick, temporary view and controller to test it. Next, I’ll replace text fields I used for input. My best choice for this bothers me. UIPickerView is one of my biggest love/hate relationship in all of iOS development.

The app from my last installment looks something like this:

While this is okay for testing the model, it is not something I’d want for users. There’s a principle I’d like to introduce: Get Good, Get Fast. When working with user interfaces, get the data from your user as quickly as possible. The more time it takes a user to input data, the less likely he or she will use the app. They will get frustrated. What they enter must be good data. Data must makes sense to the application. We refer to this as valid data.

The current user interface is fast since I can type on the keyboard, but fails miserably in the validation arena. Because I’m using a keyboard and my values from the keyboard are strings, there’s a lot of data validation code I need to be sure I’m getting good data from the user.

In the version 1.0 of Interval RunCalc, I used keyboards. I tried controlling data validation by breaking up numbers into parts. For example, time used a special controller that broke up time into three integers were easier to input but restricted themselves to certain values

I did this for HH:MM:SS, MM:SS and decimal values. Problem was I had those values everywhere in the application, so my storyboard ended up a huge mess of segues.

My rationale at the time was simple: I didn’t want to use a UIPickerView for input. I hated UIPickerViews. There’s two reasons I hate them. Picker views break the Get Fast Get Good principle on the get fast side. They are effective for no more than ideally ten to twenty items. The classic picker view was one like this with 100 components.

It takes forever to get to higher numbers, breaking get fast. I get frustrated with these in other apps, and did not want to subject my users to such a thing.

The other objection separates new developers from seasoned ones. New developers, upon learning about picker views want to abuse them. They’ll put everything in picker views, and several on the same view. They’ll throw insane amounts of data in the most confusing ways, often making the UI unusable. For example here’s six components and two picker views. You can only read it in landscape

This would take forever to input data and gets very confusing fast. I get more weird questions about bizarre uses for picker views than any other control. Most of these developers do not think like users. Users hate picker views because they are confusing and take forever to use.

There is one strength for UIPickerView: Validation. UIPickerViews constrain input. Apple uses this for the date picker, taking four elements and combining them to get a Date value.

This is how picker views are supposed to be used. But even here I hate anything over 20 rows, like the date.

The date picker gives us the clue of how to use them right: Separate components into discrete elements than can have only constrained values. Make those elements with as few elements as possible. I set a limit of twenty rows. The keyboard input was a horrible mess in version 1.0. It never worked right. Despite my objections to them, I decided to use a picker view for my input to avoid all the data validation. I want one class of UIPickerView controllers. It will adapt to the different scenarios I need: HH:MM:SS, HH:MM:SS, and two digit decimal. I’ll make this a modal view instead of the navigation view I used in the original application to get rid of all those segues. I wrote my storyboard for it, which I placed on my Main.Storyboard:

This looks like a navigation controller, but it is an independent view controller on my storyboard, which will be a modal controller. I set a storyboardID of InputController. I made an illusion of a toolbar from two buttons, a label, and a UIView behind them, arranged with some auto layout.

This is a very flexible input system, giving the user the units I’m using and giving me power over all the buttons and labels. I’ll make a view controller PickerViewController for it, and I’ll add the following outlets and actions to that view controller:

@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var toolBar: UIView!
@IBOutlet weak var unitsOfMeasureLabel: UILabel!
@IBOutlet weak var picker: UIPickerView!

@IBAction func didPressDone<span class="hljs-params">(_ sender: UIButton) {

}

@IBAction func didPressBack<span class="hljs-params">(_ sender: UIButton) {

}


Adding the Picker View 

In this article I’m more interested in the application than the implementation of a picker view. I’ll be leaving out steps. If you need to understand picker views and picker components, I’ve written out the whole process in detail which you can find here. I’ll be making a variation of that code, but understanding the way I did that will help you here.

My picker view is based on digits. No component will have more than 10 rows, speeding up the input process. Looking at the types of components I have:

  • Decimal digit – values of 0,1,2,3,4,5,6,7,8,9
  • Tens of minutes and seconds – values of 0,1,2,3,4,5
  • Time separator – a colon(:)
  • Decimal separator – a period(.)

I could add constants for this to my code, making four types of component wheels to add to my code and making some string arrays to do this.

let decimalDigit = ["0","1","2","3","4","5","6","7","8","9"]
let timeDigit = ["0","1","2","3","4","5"]
let timeSeperator = [":"]
let decimalSeperator = ["."]

That’s what I did in the article I mentioned above. There is another way to do this based on the row number and a bit of control logic. Instead of constants, I’ll use an enumeration.

enum ComponentType {

&nbsp;&nbsp;&nbsp;&nbsp;case ten,six,colon,decimal

&nbsp;&nbsp;}

I’ll make an array of this enum.

private var components = [ComponentType]()

This way I can describe any set of wheels quickly. MM:SS is [.six,.ten,.colon,.six.ten].The number of components are the size of this array

func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {

&nbsp;&nbsp;&nbsp;&nbsp;return components.count

&nbsp;&nbsp;}

For HH:MM, this would return 5. I’ll set the number of components in my datasource, based on the component type:

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    switch components[component]{
        case .ten: return 10
&nbsp;&nbsp;&nbsp;&nbsp;    case .six: return 6
&nbsp;&nbsp;&nbsp;&nbsp;    case .colon,.decimal: return 1
&nbsp;&nbsp;  }
}

Since I’m not using a string array to give me the title for a row in a component, I use the row number. The digit I want to display is equal to its row number. Make a formatted string of the row number. The exceptions are colons and decimal points, which I’ll explicitly return. I display the correct digit like this:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
&nbsp;&nbsp;&nbsp;&nbsp;switch components[component]{
&nbsp;&nbsp;&nbsp;&nbsp;    case .ten: return String(format: "%01i", row)
    &nbsp;&nbsp;&nbsp;&nbsp;case .six: return String(format: "%01i", row)
    &nbsp;&nbsp;&nbsp;&nbsp;case .colon: return ":"
    &nbsp;&nbsp;&nbsp;&nbsp;case .decimal: return "."
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}&nbsp;&nbsp;

This all depends on the correct values in the components array. I’ll add another enum, listing input formats. I have three formats for that enumeration: a double with two dight decimal, MM:SS and HH:MM:SS.

enum PickerType {

&nbsp;&nbsp;&nbsp;&nbsp;case twoDecimal,minuteSecond,hourMinuteSecond

&nbsp;&nbsp;}

I’ll write a function to set the components.

&nbsp;func setPickerComponents(for pickerType:PickerType){
&nbsp;&nbsp;&nbsp;&nbsp;self.pickerType = pickerType

&nbsp;&nbsp;&nbsp;&nbsp;switch pickerType{
&nbsp;&nbsp;&nbsp;&nbsp;    case .twoDecimal:<span class="hljs-comment">//999.99 max value
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     components = [.ten,.ten,.ten,.decimal,.ten,.ten]&nbsp;&nbsp;&nbsp;&nbsp;
        case .minuteSecond: <span class="hljs-comment">//59:59 max value
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     components = [.six,.ten,.colon,.six,.ten]
&nbsp;&nbsp;&nbsp;&nbsp;    case .hourMinuteSecond: <span class="hljs-comment">//99:59:59 max value
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;components = [.ten,.ten,.colon,.six,.ten,.colon,.six,.ten] &nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;}

The class has two data properties. When I present the view controller, I’ll set these two properties.

var units = Units.meters

&nbsp;var value = 0.0&nbsp;&nbsp;

One is the units of measure and the current value. Units is another enumeration which lists all the app’s units of measure:

enum Units {
&nbsp;&nbsp;&nbsp;&nbsp;case 
       meters,kilometers,miles,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;milesPerHour,minutesSecondsPerMile,kilometersPerHour,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hoursMinutesSecond
&nbsp;&nbsp;}

There’s a lot of cosmetic changes I’ll make depending on the units, such as displaying the units and if this is a speed, distance or time variable. I wrote a method configure to handle all this, leaving some methods to do a lot of the repetitive configuration.

func configure<(for units:Units){

&nbsp;&nbsp;&nbsp;&nbsp;switch units{
&nbsp;&nbsp;&nbsp;&nbsp;case Units.meters:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Meters"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;distance()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.kilometers:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Kilometers"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;distance()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.miles:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Miles"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;distance()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.milesPerHour:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Miles per Hour"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;paceOrSpeed()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.minutesSecondsPerMile:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setMinutesSeconds()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Minutes per Mile"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;paceOrSpeed()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.kilometersPerHour:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Kilometers per Hour "
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;paceOrSpeed()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.hoursMinutesSecond:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setHoursMinutesSeconds()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Time"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;time()
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}

I’ll add three methods for configuring the types.

func setTwoDecimal<span class="hljs-params">(){
&nbsp;&nbsp;setPickerComponents(for: .twoDecimal)
}

func setHoursMinutesSeconds<span class="hljs-params">(){
&nbsp;&nbsp;setPickerComponents(for: .hourMinuteSecond)&nbsp;&nbsp;
} &nbsp;

func setMinutesSeconds<span class="hljs-params">(){
&nbsp;&nbsp;setPickerComponents(for: .minuteSecond)
}


For the user interface side of things, I set the background color and title depending on the units so users have visual cues:

func distance(){
&nbsp;&nbsp;&nbsp;&nbsp;titleLabel.text = "Distance"
&nbsp;&nbsp;&nbsp;&nbsp;backgroundColor = UIColor.cyan
&nbsp;&nbsp;}

&nbsp;&nbsp;func paceOrSpeed(){
&nbsp;&nbsp;&nbsp;&nbsp;titleLabel.text = "Pace / Speed"
&nbsp;&nbsp;&nbsp;&nbsp;backgroundColor = UIColor.yellow
&nbsp;&nbsp;}

&nbsp;&nbsp;func time(){
&nbsp;&nbsp;&nbsp;&nbsp;titleLabel.text = "Time"
&nbsp;&nbsp;&nbsp;&nbsp;backgroundColor = UIColor.green
&nbsp;&nbsp;}&nbsp;&nbsp;

The First Test

I have enough code to test the picker now. I’ll set up a button on my test storyboard and add some code to configure the picker. I’ll add a button Picker.

I’ll make an action for this button in RootViewController.swift. This input controller is intended for modal controllers. Modals launching for a storyboard identifier makes sense in this context. I use it multiple times. It clears all that segue spaghetti I had in version 1.0. I’ll launch the controller in a modal view using the default values.

@IBAction func pickerButton<span class="hljs-params">(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;let vc = storyboard?.instantiateViewController(withIdentifier: "InputController") as! PickerViewController
&nbsp;&nbsp;&nbsp;&nbsp;present(vc, animated: <span class="hljs-literal">true, completion: <span class="hljs-literal">nil)
&nbsp;&nbsp;}

I’ll go back to the PickerViewController.swift file and add dismissal code in my actions.

@IBAction func didPressDone(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;self.dismiss(animated: true, completion: nil)
&nbsp;&nbsp;}

@IBAction func didPressBack(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;self.dismiss(animated: true, completion: nil)
&nbsp;&nbsp;}

One thing I forgot – to call configure. I’ll do that on the viewDidLoad of PickerViewController.swift

override func viewDidLoad() {
&nbsp;&nbsp;&nbsp;&nbsp;super.viewDidLoad()
&nbsp;&nbsp;&nbsp;&nbsp;picker.dataSource = self
&nbsp;&nbsp;&nbsp;&nbsp;picker.delegate = self
&nbsp;&nbsp;&nbsp;&nbsp;configure(for: self.units)
&nbsp;&nbsp;}

I’m ready to run. When I build and run, then press the picker button, I get a beautiful interface, where I can roll the individual digits.

I notice a potential bug. I ran a quarter of a marathon or 10.56 Km last weekend. That’s 10557.30 meters, which I could not enter into the app since I don’t have enough digits. I could add another two digits for 99999.99 for meters, but before I do, I’ll ask myself the question: will the user enter anything in meters?

This app is for distance runners. Distances are in kilometers or miles, never meters. That would be a change that has no use. I only care about what the user wants here, not my internal measurement system of meters. I’ll skip that change.

I do another test. I add the unit of measure in the action in RootViewController for a pace.

@IBAction func pickerButton(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;let vc = storyboard?.instantiateViewController(withIdentifier: "InputController") as! PickerViewController
&nbsp;&nbsp;&nbsp;&nbsp;vc.units = .minutesSecondsPerMile
&nbsp;&nbsp;&nbsp;&nbsp;present(vc, animated: true, completion: >nil)
&nbsp;&nbsp;}

Building and running again, I can spin the wheels there too.

Setting Values

I want to set the picker to an initial value. Inside the picker’s code I‘ll change value to a series of row indices representing the number, one digit per component. I’ll convert value to a string, then use the characters to represent rows.

If I had a 11:23 minute/mile setting, I set the string to "11:23" The code looks at a character from the left to the right as the row index for the component. The functions Int(String(character)) get me this index used in a for loop. I use the selectRow method to select the row with that number.

picker.selectRow(row, inComponent: component, animated: animated)

The Int constructor produces a nil value for any character that isn’t a digit. Those are my separators, and they always have a row value of 0. The code looks like this:

func setComponentValues(from str:String){&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;var component = 0
&nbsp;&nbsp;&nbsp;&nbsp;for character in str.characters{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if let row = Int(String(character)){
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;picker.selectRow(row, inComponent: component, animated: animated)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;picker.selectRow(0, inComponent: component, animated: animated)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;component += 1
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}

I made three functions to set the value depending on the PickerType. If their sparse code didn’t make sense before, they will now. Each converts the value to a string for that PickerType, then converts that string to the correct rows in the picker components

func setTwoDecimal(){
&nbsp;&nbsp;&nbsp;&nbsp;setPickerComponents(for: .twoDecimal)
&nbsp;&nbsp;&nbsp;&nbsp;let str = String(format:"%06.2f",value)
&nbsp;&nbsp;&nbsp;&nbsp;setComponentValues(from: str)
&nbsp;&nbsp;}

&nbsp;&nbsp;func setHoursMinutesSeconds(){
&nbsp;&nbsp;&nbsp;&nbsp;setPickerComponents(for: .hourMinuteSecond)
&nbsp;&nbsp;&nbsp;&nbsp;let hours = Int(value + 0.5) / 3600
&nbsp;&nbsp;&nbsp;&nbsp;let hoursRemainder = Int(value + 0.5) % 3600
&nbsp;&nbsp;&nbsp;&nbsp;let minutes = hoursRemainder / 60
&nbsp;&nbsp;&nbsp;&nbsp;let seconds = hoursRemainder % 60
&nbsp;&nbsp;&nbsp;&nbsp;let str =&nbsp;String(format:"%02i:%02i:%02i",hours,minutes,seconds)
&nbsp;&nbsp;&nbsp;&nbsp;setComponentValues(from: str)
&nbsp;&nbsp;}

&nbsp;&nbsp;func setMinutesSeconds(){
&nbsp;&nbsp;&nbsp;&nbsp;setPickerComponents(for: .minuteSecond)
&nbsp;&nbsp;&nbsp;&nbsp;let minutes = Int(value) / 60
&nbsp;&nbsp;&nbsp;&nbsp;let seconds = Int(value) % 60
&nbsp;&nbsp;&nbsp;&nbsp;let str = String(format:"%02i:%02i",minutes,seconds)
&nbsp;&nbsp;&nbsp;&nbsp;setComponentValues(from: str)
&nbsp;&nbsp;}

&nbsp;&nbsp;

To save myself some time I copied and pasted some code from my model to make the time strings.

In RootViewController, Add a value to the action:

@IBAction func pickerButton(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;let vc = storyboard?.instantiateViewController(withIdentifier: "InputController") as! PickerViewController
&nbsp;&nbsp;&nbsp;&nbsp;vc.units = .minutesSecondsPerMile
&nbsp;&nbsp;&nbsp;&nbsp;vc.units = 683.0 // in seconds 600 + 60 + 20 + 3 = 11min 23sec
&nbsp;&nbsp;&nbsp;&nbsp;present(vc, animated: <span class="hljs-literal">true, completion: <span class="hljs-literal">nil)
&nbsp;&nbsp;}

I’ll test this and see 11:23

Getting Values

The purpose of a input picker is the get a value from the user. To do that I’ll update value every time the picker changes. I’ll set up the picker’s delegate function to update the value in a function

&nbsp;func pickerView<span class="hljs-params">(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
&nbsp;&nbsp;&nbsp;&nbsp;updatePickerValue()
&nbsp;&nbsp;&nbsp;&nbsp;titleLabel.text = "<span class="hljs-subst">\(value)" //for testing only
&nbsp;&nbsp;}

I added a extra line for testing the value, sending the value to the title. In the app we’ll use a delegate, but that’s for the next phase, so I’ll display it here for now.

The the updatePickerValue function converts the components into a value. I built this into another switch pickerType control structure. This is the opposite of the setting the value. Take the row and convert it to a value. If it is part of a bigger number, add it with the other digits of the number. For example, for the .twoDecimal, I did this:

case .twoDecimal:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;picker.selectedRow(inComponent: 5)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let hundredth = Double(picker.selectedRow(inComponent: 5))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let tenth = Double(picker.selectedRow(inComponent: 4))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let fraction = tenth * 0.1 + hundredth * 0.01
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let ones = Double(picker.selectedRow(inComponent: 2))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let tens = Double(picker.selectedRow(inComponent: 1))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let hundreds = Double(picker.selectedRow(inComponent: 0))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let wholeNumber = hundreds * 100 + tens * 10 + ones
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value = wholeNumber + fraction

I did this explicitly since it is easier to debug than an algorithm for it. I do the same for the time-based picker types, grabbing a digit and adding it all together.

&nbsp;case .minuteSecond: //00:00 returning seconds
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var tens = Double(picker.selectedRow(inComponent: 0))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var ones = Double(picker.selectedRow(inComponent: 1))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let minutes = (tens * 10 + ones) * 60
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;tens = Double(picker.selectedRow(inComponent: 3))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ones = Double(picker.selectedRow(inComponent: 4))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let seconds = (tens * 10 + ones)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value = minutes + seconds&nbsp;&nbsp;&nbsp;

Run again and I’ll change the pace to 10:23. As expected, 623.0 is in the title.

 

I’ve built a decent picker that follows Get Good, Get Fast. All data in and out of the picker is a single value of double. What that value represents is a unit of measure. My unit of measure configures my picker for the only legitimate values. I call the picker from a modal view programmatically without a lot of confusion in the storyboard. My next step is the user interface, and hooking this up to it. In the next installment, I’ll build that UI and find I made a few bad assumptions with the picker and find some other interesting dilemmas.

Data Entry with UIPickerView

The keyboard can be a curse. Trying to validate data via keyboard can be a nightmare for many projects. One solution to this problem is using a UIPickerView to limit the values the user can enter. In this lesson, we’ll explore the UIPickerView for numerical input.

UIPickerViews are are series of wheel like scrolling objects. For more on the basics, you can read this article on them. They are made of series of components which contain rows of strings. Picker views use delegates and data sources for most of their functionality instead of actions. More often than not I see people using them totally and completely wrong. Often they are lazy man’s table views or a control exploited to pack more information than a user can handle. What they are good at is giving one pice of data with multiple parts. The digits of a number for example, or Apple’s subclass of UIPickerView UIDatePickerView, which returns a date.

Set Up the Project

For this project you’ll find a started file  advanced-picker-demo-_startwhere I added a label, picker view and a segmented control to a storyboard view controller.

2016-12-12_07-29-51

I gave some specific titles on the segmented control, 99.9, 999.9,59:59.99, and 99x, which I’ll discuss in a moment. I added an outlet for the picker and label, and an action and outlet for the segmented control.

 @IBOutlet weak var displayLabel: UILabel!
 @IBOutlet weak var picker: UIPickerView!
 @IBOutlet weak var segmentedControl: UISegmentedControl!
 @IBAction func segmentedControl(_ sender: UISegmentedControl) {
 }

Again you can find this in the starter file advanced-picker-demo-_start if you wish.

Setting Up a Picker View.

Picker views don’t have actions, but delegates and data sources, just like table views. Adopt the delegate and data source in the class declaration.

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource

Add two properties to the view controller class. components will hold the components for the UIPickerView and resultString will be the string that the picker view outputs.

var components = [[String]]()
var resultString = ""

The components property is an array of string arrays. The outer array is each digit of the picker, called a component. The inner array is the string title for a given row in the the component. The two data sources tell the picker how many elements are in the outer and inner arrays. For the outer array, Add the following:

 //:MARK - Delegates and data sources
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return components.count
    }
 

For the number of rows in each inner array, add the following:

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return components[component].count
    }

There’s two  more or less mandatory delegate methods for picker views . One we’ll add now, the other a bit later. Add the following to show the titles in the picker view

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return components[component][row]
}

Adding Component Content

The delegate and data sources you just added are pretty generic. The content to the components property are where the magic happens. Add the following function that returns a string array. We’ll use it to set a component on the picker view.

func numberPickerComponent(from char:Character) -&gt; [String]{
    switch char{
        case "9":
            return ["0","1","2","3","4","5","6","7","8","9"]
        case "5":
            return ["0","1","2","3","4","5"]
        case "x":
            return ["0"," 1/16","1/8","3/16","1/4","5/16","3/8","7/16","1/2","9/16","5/8","11/16","3/4","13/16","7/8","15/16"]
        default:
            return [String(char)]
    }
}

This function returns an array of strings that starts at 0 and goes to the digit indicated. You could make a case for all the numbers between 0 a 9, but I only picked a few for the purposes I have in mind. Most decimal numbers will be 0 through 9. Time functions will need 0 to 5 for minutes and seconds. The x will stand for fractions. I set my fractions to increments of 1/16 to 15/16. The default returns a string of a single character for all other cases.

With these four cases, you can create formats in your picker from a control string. I stuck those control strings in the segmented control, but you could assign them directly of course. A string of 99.9 is a value from 0 to 99.9. A string of 99x is a string of 0 to 99 15/16. While the UIDatePickerView gets times, if you need a TimeInterval for values with less than second, you’ll find it difficult. 59:59.99 give us times from 0 seconds to 59 minutes 59.99 seconds or 3599.99 seconds.

Add the function to take a string and make it into an array of components. This iterates over the string, calls the numberPickerComponent function you just defined to grab an array, and adds that array to the components array. Once assembled, the function returns the completed array.

 func numberPickerComponents(from string:String)->[[String]]{
        
        var components = [[String]]()
        for char in string.characters{
            components += [numberPickerComponent(from:char)]
        }
        return components
    }

Since I’m changing the pickerComponents in a segmented control, on a change of segment, the code updates the picker. It grabs the string for the segment’s titles and makes that the components. Add this:

    @IBAction func segmentedControl(_ sender: UISegmentedControl) {
        let index = sender.selectedSegmentIndex
        let pickerComponentString = segmentedControl.titleForSegment(at: index)!
        components = numberPickerComponents(from: pickerComponentString)
        resetPicker()
            }

This function calls a function we haven’t defined yet, resetPicker. There’s two jobs for the resetPicker function. One is to reload the components of the picker so the correct ones are there. the reloadAllComponenets method of UIPickerView does that. The second can be a bit tricky. The wheels will be inaccurate if you leave the setting from one format to another. I took the simplest approach and zero the components with a loop that selects the first element in each component. The selectRow:inComponenet:Animated: method can animate the change, which I set to true to roll the components back to zero. Add this to your code:

 func resetPicker(){
     picker.reloadAllComponents()
     for index in 0..<components.count{
       picker.selectRow(0, inComponent: index, animated: true)
     }
 }

This code initializes all this in viewDidLoad, setting the delegate and data source to self, and setting the initial segement control, picker view and components to the first segment. Add this to viewDidLoad:

override func viewDidLoad() {
   super.viewDidLoad()
   picker.dataSource = self
   picker.delegate = self
   segmentedControl.selectedSegmentIndex = 0
   let pickerComponentString = segmentedControl.titleForSegment(at: 0)!
   components = numberPickerComponents(from: pickerComponentString)
}

That sets the picker to display correctly. We’d like some output, in this case a string we’ll parse later. The last delegate function is the selection function. I’ll output the selection to the label. Add this to your code where you placed your data sources.

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        resultString = ""
    
        displayLabel.text = resultString
    }

This is another tricky spot. The parameters of the selection method only gives us the component that changed, not all the components. There’s a picker view method selectedRow(inComponent:) which can get us the index of any component. I loop through all the components and concatenate each to resultString. Add this below resultString:

for index in 0..<components.count{
    let digit = components[index][pickerView.selectedRow(inComponent: index)]
    resultString += digit
}

This almost works. It still has a bug. If using fractions, this code will make 33 1/3 be 331/3. For cases where the component is larger than one character, add an extra space. Add this under the let digit assignment:

if digit.characters.count > 1 {
    resultString += " " 
}

Build and run. The picker view will look like this.

2016-12-12_07-31-26
You can dial a number of 3.1.

2016-12-12_07-32-14
Set the segmented control to 999.99. Dial up 203.14.
2016-12-12_07-33-06

Go to the time of 59:99.00, put a time of 12:54.37 and you get this
2016-12-12_07-34-30
Finally click on 99X for the fractions and try 12 3/8
2016-12-12_07-35-25

You get the values showing up as a string in the title. However you may not want a string for any of these, but a double instead. We’ll need to parse the string into a number. In next week’s lesson, we’ll tackle that part of the picker.

The Whole Code

You can find the finished lesson here for download:advanced-picker-demo.

//
//  ViewController.swift
//  Advanced Picker Demo
//
//  Created by Steven Lipton on 12/12/16.
//  Copyright © 2016 Steven Lipton. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate,UIPickerViewDataSource {
    
    var components = [[String]]()
    var resultString = ""
    
    
    @IBOutlet weak var displayLabel: UILabel!
    @IBOutlet weak var picker: UIPickerView!
    @IBOutlet weak var segmentedControl: UISegmentedControl!

    @IBAction func segmentedControl(_ sender: UISegmentedControl) {
        let index = sender.selectedSegmentIndex
        let pickerComponentString = segmentedControl.titleForSegment(at: index)!
        components = numberPickerComponents(from: pickerComponentString)
        resetPicker()
    }
    
    func numberPickerComponent(from char:Character) -> [String]{
        switch char{
        case "9":
            return ["0","1","2","3","4","5","6","7","8","9"]
        case "5":
            return ["0","1","2","3","4","5"]
        case "x":
            return ["0"," 1/16","1/8","3/16","1/4","5/16","3/8","7/16","1/2","9/16","5/8","11/16","3/4","13/16","7/8","15/16"]
        default:
            return [String(char)]
        }
    }
    
    func numberPickerComponents(from string:String)->[[String]]{
        
        var components = [[String]]()
        for char in string.characters{
            components += [numberPickerComponent(from:char)]
        }
        return components
    }
    func resetPicker(){
        picker.reloadAllComponents()
        for index in 0..<components.count{ picker.selectRow(0, inComponent: index, animated: true) } } override func viewDidLoad() { super.viewDidLoad() picker.dataSource = self picker.delegate = self segmentedControl.selectedSegmentIndex = 0 let pickerComponentString = segmentedControl.titleForSegment(at: 0)! components = numberPickerComponents(from: pickerComponentString) } //:MARK - Delegates and data sources func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return components.count
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return components[component].count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return components[component][row]
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        resultString = ""
        for index in 0..<components.count{ let digit = components[index][pickerView.selectedRow(inComponent: index)] if digit.characters.count > 1 {//add space if more than one character
                resultString += " " //add space if more than one character
            }
            resultString += digit
        }
        displayLabel.text = resultString
    }

}

Converting Objective C to Swift : The Circular Picker View Example

Screenshot 2015-03-01 14.59.10Swift is a new language. Objective C is not. Sometimes you have some Objective C code and want to make it into Swift code. I had a case of that this week when a reader asked me about continuous picker view wheels. If you are familiar with the date picker it goes from 0 to 59 and then loops back to 0, making a continuous wheel. The UIPickerView does not have this ability. When asked, I did not know how to do this. The reader found some code in Objective C that did that. I did a little web searching and I did find a solution. Of course it was in Objective C, not Swift.

I’ve wanted to write a piece on converting from Objective C to Swift for a while. I didn’t have a good example to use. This makes a really good example. We’ll discuss some things you should know and try an example of converting a method for a UIPickerView from Objective C into Swift.

Header Files and Scope

Objective C uses two files for a class, unlike Swift’s single file for a class. A primary reason for this is sharing.  Some data is shared in a class, some isn’t. We refer to how much something shares as its scope. Scope rules are very different between the two languages. One of those two files in Objective C is a header file or .h file. The .h file has information that is public in scope. A public scope allows sharing. Anything private and not shared gets declared in the other file, the  implementation file. Implementation files have  a .m extension. The .h file includes properties, methods target-actions, outlets, and often protocols for delegates. It is in the header file that you find most of the class definition. The header file has no code though: it is only declarations. You will repeat all your methods and target actions in the implementation file when you write the code for it.

In the code I found the header looks like this:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<uipickerviewdatasource,uipickerviewdelegate>
@property (weak, nonatomic) IBOutlet UIPickerView *myPicker;
@property  NSInteger maxRows;

@end

In the header file, you will find a series of tags beginning with @. You’ll find on each property a @property tag. These will be the public properties. We have one of these as an outlet to our picker view:

@property (weak, nonatomic) IBOutlet UIPickerView *myPicker;

Let’s dissect this outlet from a Swift perspective. @property (weak, nonatomic) IBOutlet sets an outlet with a weak variable. Since Swift has an even more automatic version of Automatic Reference Counting(ARC) than Objective C, we ignore the nonatomic part. Next we have the class of the identifier, UIPickerView. Finally, we have the identifier for the property *myPicker. the asterisk (*) means  this is a pointer, which is true of most object identifiers in Objective C. Pointers in Objective C can have nil values,. It’s a good idea to their Swift equivalent an optional value.

This translates in Swift to

@IBOutlet weak var myPicker: UIPickerView!

If you never saw the difference between the two languages, you might begin to see why Swift is so speedy for coding. The outlet is merely @IBOutlet. We have a weak variable so next we have weak var. Next comes the identifier myPicker with the class UIPickerView as an optional.
Swift encourages assignment of values to variables and constants at declaration. Objective C does not. In Objective C, you declare in one place and assign in another. Often the assignment happens in the viewDidLoad method of your .m file. When reading Objective C code declarations, keep the viewDidLoad handy. For example our .h file has this line:

  @property  NSInteger maxRows;

in the .m file we have this in viewDidLoad:

self.maxRows = 10;

For all properties, Objective C requires the self identifier. These two lines equal the one line in Swift.:

let maxRows = 10

Which assigns maxRows equal to an Int of 10 and sets the type to Int. Of course this also makes this a constant, which is not the case in Objective C.

There is also an @interface tag in the .h file. Our properties and any public methods are found between this tag and the @end tag.

@interface ViewController : UIViewController<uipickerviewdatasource,uipickerviewdelegate>
…
@end

The @interface tag tells us the identifier of this class, and its superclass. In this app it is UIViewController. In angle brackets after the superclass is a list of adopted protocols. In our case we adopted the picker view data source and delegate. Again Swift simplifies this to essentially one line — and a bracket

class ViewController:UIViewController,UIPickerViewDataSource,UIPickerDelegate{
}

We have two @interface tags in any Objective-C class. The second is in the .m file, and lists private properties. For example we have this:

@interface ViewController ()
    @property NSInteger maxElements;
@end

Swift simplifies this to a mere keyword: private. The viewDidload  method tells us to set this to 10,000. Given that information we get this:

 private let maxElements = 10000

Putting that all together, we can take the header file, plus  the @interface and the viewDidLoad in the implementation file to translate them into Swift:

import UIKit
class ViewController:UIViewController,UIPickerDataSource,UIPickerDelegate{
    let maxRows = 10
    private let maxElements = 10000
    @IBOutlet weak var myPicker:UIPickerView
}

The Meat of the Matter: The Implementation File

Let’s look at the implementation file now and figure out what it is doing. I’ll assume you know about UIPickerView and its delegates.  If you don’t, read this first. The Objective C file is this:

#import "ViewController.h"

@interface ViewController ()
    @property NSInteger maxElements;
@end

@implementation ViewController

#pragma mark delegates and data source

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.maxElements;
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component{
    NSString *myString;
    NSInteger myRow = row % self.maxRows;
    myString = [NSString stringWithFormat:@"%li",(long)myRow];
    return myString;
}

#pragma mark life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.maxElements = 10000;
    self.maxRows = 10;
    self.myPicker.delegate = self;
    self.myPicker.dataSource = self;
    [self.myPicker selectRow:self.maxElements / 2  inComponent:0 animated:NO];
}

@end

If you have never worked in Objective C before, your biggest challenge is how they put stuff backwards from Swift, C++, Java or most any other language.

Objective C bases its syntax on an older language, Smalltalk. It was a Smalltalk demonstration that inspired Steve Jobs to come up with the Macintosh in the early 1980’s. Both Smalltalk and Objective C look at objects very literally. You state what your object is and then what you want to do with it. You enclose that in square brackets. For example we have

[super viewDidLoad];

which runs the superview’s viewDidLoad. Swift writes that as a function

super.viewDidLoad()

Since this is a picker view, we need to add two data source methods to tell us about our data and one delegate method. Let’s look at one of those methods:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

This implements one of our two required data source methods. We have one component in our picker view, so we return 1. The minus sign at the beginning of the method declaration tells the compiler and developer that this is an instance method. If it was a plus it would be a class method. Next,  the return type is in parentheses, followed by the method identifier. If there are parameters, the parameter list follows. In Swift that looks like this:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}

The syntax is very different between the two, but the same information is there. The next data source method works the same, returning a value for the number of rows in the picker, which in this case is a lot.

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return self.maxElements;
}

We use maxElements to set this size, which we know is 10,000 rows. Why do we need that many rows? The answer lies in the delegate method, titleForRow:

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component{
    NSInteger myRow = row % self.maxRows;
    NSString *myString = [NSString stringWithFormat:@"%li",(long)myRow];
    return myString;
}

The declaration tells us we return a string, and have the parameters of the picker view, the row and the component. The code declares an NSInteger, called myRow which is the modulo of row and maxRows. We take this new value, convert it to a NSString, and then return the string. Unlike properties, in methods we can declare and assign at the same time. However, we need to declare the type when we do.

What does this do? The method takes a massive set of numbers and has a row in that set of 10,000. It takes the remainder of row divided by maxRows. That remainder will repeat between 0 and maxrows - 1.  In effect, the picker repeats between 0 and 9 in our case. If the number for maxElements is big enough, it is unlikely that we will run out of numbers for repetition. Since these are integers, you’ve used a small amount of memory to do this.

You can write the method like this in Swift:

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        let myRow = row % maxRows
        let myString = String(format: "%i", myRow)
        return myString
    }

We returned the string as an optional. When converting from Objective-C to Swift, anything that is a pointer is best converted as an optional.

But we are not done yet. The Objective C code still has the viewDidload method.

- (void)viewDidLoad {
[super viewDidLoad];
self.maxElements = 10000;
self.maxRows = 10;
self.myPicker.delegate = self;
self.myPicker.dataSource = self;
[self.myPicker selectRow:self.maxElements / 2 inComponent:0 animated:NO];
}

The viewDidload method does not need to assign initial values in Swift. That happens when we declare a value. Objective C requires you to explicitly say where something is with self, while Swift is better at guessing. We can get rid of the first two assignments, and get rid of all the self references, though you can leave them there if you wish. The last line of the method makes a call to myPicker and selects a specific row in the picker: 5,000. This way if we roll up or down we will get a repeat. All this in Swift looks like this:

override func viewDidLoad() {
        super.viewDidLoad()
        myPicker.dataSource = self
        myPicker.delegate = self
        myPicker.selectRow(maxElements / 2, inComponent: 0, animated: false)
    }

Our Swift file looks like this now:


import UIKit

class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
    //MARK: Properties
    let maxRows = 10
    private let maxElements = 10000

    //MARK: Outlets
    @IBOutlet weak var myPicker: UIPickerView!
    func platypus(){
        //doesn't do much

    }
    //MARK: Delegates and DataSources
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return maxElements
    }
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        let myRow = row % maxRows
        let myString = String(format: "%i", myRow)
        return myString
    }

    //MARK: Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        myPicker.dataSource = self
        myPicker.delegate = self
        myPicker.selectRow(maxElements / 2, inComponent: 0, animated: false)
        platypus()
    }

}

If you’d like to try this code out, make a new single view project. Drag a Picker View  and a label out on to the storyboard. Make it look like this:

Screenshot 2015-03-01 13.56.14

Copy the code above into the ViewController.swift file of your project.

Using the assistant editor, control-drag from the picker to the myPicker outlet. Control-drag from the I want coffee!! label to the Assistant editor. Name the new outlet statusLabel.

Build and run:

 

Screenshot 2015-03-01 14.08.54

 

Using Text Arrays

Not everyone will want the row number. Most likely, you will want something else listed in your picker view. If you want to use text, set up an array like this:

private let coffee = ["Coffee","Latte","Mocha","Machiatto","Frappucino","Espresso","Red Eye","Black Eye","Espresso","Irish Coffee"]

Change the pickerView:titleForRow: to this.

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        let myRow = row % coffee.count
        //let myRow = row % maxRows
        //let myString = String(format: "%i", myRow)
        let myString = coffee[myRow]
        return myString
    }

We take the repeating row and use that for the index to the array. Build and run:

 

Screenshot 2015-03-01 14.09.28

 

Returning Values

To get a value from a selected wheel, we use the modulo again. This time in the didSelectRow delegate method. Add this to the code:

func pickerView(pickerView: UIPickerView,didSelectRow row: Int,inComponent component: Int){
        let myRow = row % coffee.count
        let myString = coffee[myRow]
        statusLabel.text = "I love " + myString + "s"
    }

Build and run:

Screenshot 2015-03-02 07.54.18

You can add one more line. For most simple cases it isn’t necessary if you have plenty of space to spin, but there may be times you need to limit your space, or prevent running out of space. You can add this or something like it to didSelectRow:

pickerView.selectRow((maxElements / 2) + row, inComponent: 0, animated:false)

I’d leave maxElements at 10000, and this means maxElements/2 is 5000. Since 5000 a number ending in 0,  we can position the picker back at the middle plus offset of myRow. Whenever the wheel stops, we are back a the middle. Note if maxElements/2 does not divide evenly to 0, you might run into problems and need a little more complicated math.

This is the basics of building a repeating picker view. It also illustrates some of the important issues you need to watch if converting between old Objective-C and Swift. These are not the only issues. Apple has an  e-book on the subject of using Objective-C and Swift, and it is worth the time reading.

The Whole Objective – C Code

//
//  ViewController.h
//  InfinitePicker
//
//  Created by Steven Lipton on 2/28/15.
//  Copyright (c) 2015 MakeAppPie.Com. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<uipickerviewdatasource,uipickerviewdelegate>
@property (weak, nonatomic) IBOutlet UIPickerView *myPicker;
@property  NSInteger maxRows;

@end
//
//  ViewController.m
//  InfinitePicker
//
//  Created by Steven Lipton on 2/28/15.
//  Copyright (c) 2015 MakeAppPie.Com. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
    @property NSInteger maxElements;
@end

@implementation ViewController

#pragma mark delegates and data source

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.maxElements;
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component{
    NSString *myString;
    NSInteger myRow = row % self.maxRows;
    myString = [NSString stringWithFormat:@"%li",(long)myRow];
    return myString;
}

#pragma mark life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.maxElements = 10000;
    self.maxRows = 10;
    self.myPicker.delegate = self;
    self.myPicker.dataSource = self;
    [self.myPicker selectRow:self.maxElements / 2  inComponent:0 animated:NO];
}

@end

The Whole Swift Code

//
//  ViewController.swift
//
//  Created by Steven Lipton on 2/28/15.
//  Copyright (c) 2015 MakeAppPie.Com. All rights reserved.
//

import UIKit

class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
    //MARK: Properties
    let maxRows = 100
    private let maxElements = 10000
    private let coffee = ["Coffee","Latte","Mocha","Machiatto","Frappucino","Espresso","Red Eye","Black Eye","Espresso","Irish Coffee"]

    //MARK: Outlets
    @IBOutlet weak var myPicker: UIPickerView!
    @IBOutlet weak var statusLabel: UILabel!

    //MARK: Delegates and DataSources
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return maxElements
    }
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        //let myRow = row % maxRows
        //let myString = String(format: "%i", myRow)
        let myRow = row % coffee.count
        let myString = coffee[myRow]
        return myString
    }

    func pickerView(pickerView: UIPickerView,didSelectRow row: Int,inComponent component: Int){
        let myRow = row % coffee.count
        let myString = coffee[myRow]
        statusLabel.text = "I love " + myString + "s"
        //if you want to use less elements in maxElements
        // or prevent ever running to the end of the list in your pickerview
        //you can set yourself back to the middle. It is not necessary for most cases.
        pickerView.selectRow((maxElements / 2) + row, inComponent: 0, animated:false)
    }

    //MARK: Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        myPicker.dataSource = self
        myPicker.delegate = self
        myPicker.selectRow(maxElements / 2, inComponent: 0, animated: false)
    }

}