gpt4 book ai didi

objective-c - UIPickerView viewForRow UILabel 忽略框架

转载 作者:行者123 更新时间:2023-12-01 17:43:27 27 4
gpt4 key购买 nike

我正在使用 UILabel 作为我的 UIPickerView 的自定义 View ,并且我试图将标签从左侧填充 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;
}

谢谢!

最佳答案

不要使用 UILabel直接地。对你来说最简单的方法是...

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

  • pickerView:widthForComponent:
  • pickerView:rowHeightForComponent:

  • ...而不是基于 UIView 创建自定义类并返回这个对象。在您的自定义 UIView , 添加 UILabel subview 和移动 UILabellayoutSubviews你的类(class)。像这样的东西...
    // 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: .

    关于objective-c - UIPickerView viewForRow UILabel 忽略框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12847219/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com