1

我正在使用 UILabel 作为我的 UIPickerView 的自定义视图,并且我试图将标签从左侧填充 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中,添加UILabel子视图并移入UILabellayoutSubviews的班级。像这样的东西...

// 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

...并返回您MyPickerViewpickerView:viewForRow:forComponent:reusingView:.

于 2012-10-11T20:15:48.003 回答