Search code examples
objective-ciosalgorithmuipickerview

algorithm for custom DatePicker


I'm working on a custom UIPickerView that will show times. I need them to match what the website shows below.

The time will start at x but for now that is midnight (it can be anytime). It will then increment intervals of i. For the below image i = 7.

The problem I am running into is when I change the hour, for example 1am, the minutes will need to change as well so that the user can only pick a minute for that hour, that is in increments of i, but I'm not sure the correct algorithm to run.

For now I am using 60 % i == 0 then use the UIDatePicker and setting minuteInterval to i, but if 60 % i != 0 that is where I need to use this customer picker.

Can anyone help me with an algorithm that would provide me the number of rows for the hours, minutes and as well populate the hours and minutes based on the interval?

enter image description here


Solution

  • I can't tell you anything about objective-c, or ios, or uipickerview... For the algorithm. Here is some pseudo code in no language in particular:

    i = 7      // this is i in your example
    offset=420 // This is where you could say you want 
               // to start at 7:00 (420 minutes after midnight) 
               // you could use any number here obviously.
    counter = offset
    while (counter<1440+offset){
        counter = counter+i
        minutes = counter%60
        hours   = counter/60  // Use integer division 
    }
    

    The modulous gives you your minutes every time by giving you the remainder.. So in your example minutes would go from 56 => 63 => 3 which is what you want.

    if you just want to know what the minutes and hours will be for a given interval (suppose the intervals go from 0 to 206 (there are 206 7 minute intervals in a day) then you would do the following:

    minutes = (i*intervalNum) % 60
    hours =   (i*intervalNum) / 60    // Integer division!
    

    If you need the number of intervals in a time period you could do the following:

    keep a hashmap (again I don't know how objective-c handles these) that maps an hour to a list of the minutes that mark intervals.  In your example you could have a hashmap that looks like:
    
    {0 => (0,7,14,21,28,35,42,49,56),
     1 => (3,10,17,24,31,38,45,52,59),
     2 => (6,13,20,27,34,41,48,55),
     ...
    }
    

    You would build this map during the first round through. To get the number of intervals in the 2-3 timeslot just return map[2].length (or whatever its equivalent).

    Obviously this is one of MANY ways to do this and one would need much more context to go into any further detail.

    Good Luck