UIPickerView viewForRow UILabel忽略帧

Leo*_*eon 1 objective-c uipickerview ios

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

zrz*_*zka 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
Run Code Online (Sandbox Code Playgroud)

...和回报您MyPickerViewpickerView:viewForRow:forComponent:reusingView:.

  • @maddy WTF?天啊,这种黑客……如果字体被改变怎么办?如果……正确执行怎么办…… (2认同)