UIPickerView viewForRow UILabel忽略帧

时间:2012-10-11 19:38:34

标签: objective-c ios uipickerview

我正在使用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;
}

谢谢!

1 个答案:

答案 0 :(得分:6)

请勿直接使用UILabel。最简单的方法是......

通过......定义宽度/高度

  • pickerView:widthForComponent:
  • pickerView:rowHeightForComponent:

...而不是基于UIView创建自定义类并返回此对象。在您的自定义UIView中,添加UILabel子视图,然后在您班级的UILabel中移动layoutSubviews。像这样......

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