Search code examples
iphoneiosxcodeformattinguipicker

Make UIPicker have at least one foot value?


Just like with Apples timer app, you can't select "0". You have to choose at least 1 hour or 1 minute. Here is how I'm formatting the textfield for the picker..

//Formats the textfield based on the pickers.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

NSString *result = [feetArray objectAtIndex:[feetPicker selectedRowInComponent:0]];

result = [result stringByAppendingFormat:@"%@ft", [feetArray objectAtIndex:[feetPicker selectedRowInComponent:1]]];
result = [result stringByAppendingFormat:@" %@", [inchArray objectAtIndex:[inchesPicker selectedRowInComponent:0]]];
result = [result stringByAppendingFormat:@"%@", [inchArray objectAtIndex:[inchesPicker selectedRowInComponent:1]]];
result = [result stringByAppendingFormat:@" %@in", [fractionArray objectAtIndex:[fractionPicker selectedRowInComponent:0]]];

RiseTextField.text = result;
}

What I need to if they choose "0" all the way across, I want the foot to automatically go to 1 on the picker. I have 3 pickers in my view made as one. 2 components for feet, 2 components for inches then 1 component for fractions. so its displayed in the textfield like 10f 09 1/16in.


Solution

  • Essentially what you want to do is this:(assuming that row 0 contains the zero values)

    -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
        if (([feetPicker selectedRowInComponent:0] == 0)&&
            ([feetPicker selectedRowInComponent:1] == 0)&&
            ([inchesPicker selectedRowInComponent:0] == 0)&&
            ([inchesPicker selectedRowInComponent:1] == 0)&&
            ([fractionPicker selectedRowInComponent:0] == 0)){
            // All values zero
            [feetPicker selectRow:1 
                      inComponent:1 
                         animated:YES];
            return;
        }
        // Handle valid value
    }
    

    On a side note consider using an NSMutableString for result. Then instead of creating a new NSString every line you can just call [result appendFormat:@".... to modify the one you have.