Search code examples
iosobjective-cuipickerview

Issue with UIPickerView fixed label for each component on iOS 6


I want to display a UIPickerView with some text hardcoded for each component. Something like "Hours" and "Mins". Now, I could achieve this by creating and putting the labels as subviews to picker view. This works fine for iOS 7 & above.

But for iOS 6, my labels are overlapped by UIPickerView components so they are not visible. How could I achieve this view for iOS 6 where for each component, values are tagged to a fixed label so user know what they are selecting.


Solution

  • For the benefit of others, this is how I achieved this (based on Frog's suggestion):

    - (void)setDatePickerView:(MyCustomCell *)iCell {
        UIView *inputView = [[UIView alloc] init];
    
        // Add Picker First
        UIPickerView *pickerView = [[UIPickerView alloc] init];
        pickerView.delegate = self;
        pickerView.tag = 100;
    
        int height = 30;
        int offsetY = pickerView.frame.size.height / 2 - height / 2;
    
        // Add a line on top of selection
        if ([Utilities isIOS7orAbove]) {
            UIImageView *topLineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, offsetY - 2, pickerView.frame.size.width, 1)];
            [topLineView setBackgroundColor:[UIColor grayColor]];
            [pickerView addSubview:topLineView];
        }
    
        [inputView addSubview:pickerView];
    
        // Add Minute Label
        CGFloat minLabelX = [Utilities isIOS7orAbove] ? 97 : 90;
        CGFloat labelYM = [Utilities isIOS7orAbove] ? 0.0 : 1.0;
        CGFloat labelW = 50;
    
        UILabel *minutesLabel = [[UILabel alloc] initWithFrame:CGRectMake(minLabelX, offsetY - labelYM, labelW, height)];
        minutesLabel.text = @“Mins";
        minutesLabel.font = [UIFont systemFontOfSize:kFontSize22];
        minutesLabel.backgroundColor = [UIColor clearColor];
        minutesLabel.textColor = [UIColor blackColor];
        [inputView addSubview:minutesLabel];
    
        // Now Add Seconds Label
        CGFloat secLabelX = [Utilities isIOS7orAbove] ? 230 : 218;
        UILabel *secondsLabel = [[UILabel alloc] initWithFrame:CGRectMake(secLabelX, offsetY - labelYM, labelW, height)];
        secondsLabel.text = @“Secs";
        secondsLabel.font = [UIFont systemFontOfSize:kFontSize22];
        secondsLabel.backgroundColor = [UIColor clearColor];
        secondsLabel.textColor = [UIColor blackColor];
        [inputView addSubview:secondsLabel];
    
        iCell.inputField.inputView = inputView;
    }