1

UIPickerView のカスタム ビューとして UILabel を使用しており、ラベルを左から 10px 程度パディングしようとしています。ただし、UILabel をどのフレームに設定しても無視されます。

私は基本的に、年コンポーネントに「不明」オプションを使用して、日付ピッカーを作成しようとしています。私はiOS開発の初心者です。UIDatePicker をサブクラス化し、「不明な」オプションを追加することは可能ですか?

これが私のコードです:

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

    if (!tView)
    {
        tView = [[UILabel alloc] initWithFrame:** Any CGRect here **];

        tView.backgroundColor = [UIColor redColor];
        tView.font = [UIFont boldSystemFontOfSize:16.0];

        if (component == 0)
        {
            tView.textAlignment = NSTextAlignmentCenter;
        }
    }

    // Set the title
    NSString *rowTitle;

    if (component == 0)
    {
        rowTitle = [NSString stringWithFormat:@"%d", (row + 1)];
    }
    else if (component == 1)
    {
        NSArray *months = [[NSArray alloc] initWithObjects:@"January", @"February", @"March", @"April", @"May", @"June", @"July", @"August", @"September", @"October", @"November", @"December", nil];
        rowTitle = (NSString *) [months objectAtIndex:row];
    }
    else if (component == 2)
    {
        if (row == 0)
        {
            rowTitle = @"- Unknown -";
        }
        else
        {
            NSDateFormatter *currentYearFormat = [[NSDateFormatter alloc] init];
            currentYearFormat.dateFormat = @"YYYY";
            NSInteger currentYear = [[currentYearFormat stringFromDate:[NSDate date]] intValue];

            rowTitle = [NSString stringWithFormat:@"%d", (currentYear - row)];
        }
    }

    tView.text = rowTitle;

    return tView;
}

ありがとう!

4

1 に答える 1

6

UILabel直接使用しないでください。あなたにとって最も簡単な方法は...

... を介して幅/高さを定義します

  • pickerView:widthForComponent:
  • pickerView:rowHeightForComponent:

... に基づいてカスタム クラスを作成しUIView、このオブジェクトを返します。カスタムで、サブビューをUIView追加し、クラスに移動します。このようなもの ...UILabelUILabellayoutSubviews

// MyPickerView.h
@interface MyPickerView : UIView
  @property (nonatomic,strong,readonly) UILabel *label;
@end

// MyPickerView.m
@interface MyPickerView()
  @property (nonatomic,strong) UILabel *label;
@end

@implementation MyPickerView
  - (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if ( self ) {
      _label = [[UILabel alloc] initWithFrame:CGRectZero];
    }
    return self;
  }

  - (void)layoutSubviews {
    CGRect frame = self.bounds;
    frame.origin.x += 10.0f;
    frame.size.width -= 20.0f;
    _label.frame = frame;
  }
@end

...そしてあなたを返しMyPickerViewますpickerView:viewForRow:forComponent:reusingView:

于 2012-10-11T20:15:48.003 に答える