简体   繁体   中英

How align selected row like other row in uipickerview

I use custom label for uipickerview and use this code

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:     (NSInteger)component reusingView:(UIView *)view {
    UILabel *pickerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 0.0f, [pickerView   rowSizeForComponent:component].width - 20.0f, [pickerView   rowSizeForComponent:component].height)];
    pickerLabel.adjustsFontSizeToFitWidth = YES;
    if (component == 0) {
      pickerLabel.text = [aCAddWeightData.intValueWeights objectAtIndex:row];
      pickerLabel.textAlignment= NSTextAlignmentRight;
    } else {
      pickerLabel.text = [aCAddWeightData.floatValueWeights objectAtIndex:row];
      pickerLabel.textAlignment= NSTextAlignmentLeft;
    }
    return pickerLabel;
}

and i got it 在此输入图像描述

I want align selected row and other row from vertical line, how i can do this?

As I see, this occurs only when we have 2 components and haven't set width for components. I found a workaround for this. Actually it's not clear why it works, but, when we set width for component value less than pickerView.frame.size.width/3 (in case when we've 2 components), we get selected row aligned as well as unselected rows.

// implement UIPickerViewDelegate's method
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return 80;  // any value less than 106.6, assuming pickerView's width = 320
}

It works fine for me.

From Apple docs here :

You cannot customize the picker view's selection indicator on iOS 7.

Edit: Try removing the .textAlignment properties altogether.

This solution works with any UIPickerView, customized or not.

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    CGFloat width = pickerView.frame.size.width;

    NSUInteger count = pickerView.numberOfComponents;
    //If count is wrong, use this instead:
    //NSUInteger count = yourDatasource.count;
    if(count > 1){
        width /= count;
    }

    return width;
}

And if you need alignment, it's in this method:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* label = (UILabel*)view;

    if (!label){
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:13.0f]];
        //Set here alignment depending on your component if needed
        [label setTextAlignment:NSTextAlignmentCenter];
    }

    [label setText:@"Your text from your datasource"];

    return label;
}

Note: UIPickerViewDelegate of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM