如何将所选行与uipickerview中的其他行对齐

时间:2013-12-24 18:12:28

标签: ios iphone objective-c uipickerview

我为uipickerview使用自定义标签并使用此代码

- (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;
}

我得到了它enter image description here

我想从垂直线对齐选定的行和其他行,我该怎么做?

3 个答案:

答案 0 :(得分:4)

正如我所看到的,只有当我们有2个组件并且没有为组件设置宽度时才会发生这种情况。我找到了解决方法。实际上还不清楚它为什么会起作用,但是,当我们将组件值的宽度设置为小于pickerView.frame.size.width / 3时(如果我们有2个组件),我们会选择行对齐以及未选择的行。

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

它适用于我。

答案 1 :(得分:0)

来自Apple docs here

  

您无法在iOS 7上自定义选择器视图的选择指示器。

编辑:尝试完全删除.textAlignment属性。

答案 2 :(得分:0)

此解决方案适用于任何UIPickerView,无论是否自定义。

- (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;
}

如果你需要对齐,那就是这个方法:

- (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;
}

注意:UIPickerViewDelegate当然。