Search code examples
iostimeruipickerview

UIPickerView centered columns


I am creating a custom time picker, using this question as a guide and my columns don't line up.

enter image description here

Here is where I create the hour and minutes labels:

UILabel *hourLabel = [[UILabel alloc] initWithFrame:CGRectMake(datePickerCell.pickerView.frame.size.width/2 - 25, datePickerCell.pickerView.frame.size.height / 2 - 15, 50, 30)];
            hourLabel.text = @"hour";
            [datePickerCell.pickerView addSubview:hourLabel];

            UILabel *minsLabel = [[UILabel alloc] initWithFrame:CGRectMake(datePickerCell.pickerView.frame.size.width - 25, datePickerCell.pickerView.frame.size.height / 2 - 15, 50, 30)];
            minsLabel.text = @"min";
            [datePickerCell.pickerView addSubview:minsLabel];

Here is my viewForRow:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *columnView = [[UILabel alloc] initWithFrame:CGRectMake(pickerView.frame.size.width/4  - 15, 0, 35, 30)];
    columnView.text = [NSString stringWithFormat:@"%lu", row];
    columnView.textAlignment = NSTextAlignmentRight;

    return columnView;
}

How do I get the 0 to line up with the bottom numbers?


Solution

  • Try implementing the following delegate method:

    - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
    

    Reduce the width to the minimum space you need and they should line up better since this prevents it moving the text to the left or right. Also try and center the text where it can go from 1 to 2 characters to force things to stay in line.