0

我正在尝试创建一个UITextField显示日期选择器而不是键盘的自定义。我已经将故事板中的文本字段更改为使用 DateTextField 自定义类,但是,仍然显示键盘而不是日期选择器。请注意,文本字段位于UITableviewCell. 另外,我不确定这是否是创建工具栏的正确方法:

self.datePickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.superview.bounds.size.width, 44)];



@interface DateTextField : UITextField

@property (strong, nonatomic) UIDatePicker *datePicker;
@property (strong, nonatomic) UIToolbar *datePickerToolbar;

@end


@implementation DateTextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.datePicker = [[UIDatePicker alloc] init];
        self.datePicker.datePickerMode = UIDatePickerModeDate;
        self.datePickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.superview.bounds.size.width, 44)];
        [self.datePickerToolbar setBarStyle:UIBarStyleBlackTranslucent];
        UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(setDatePickerValue:)];
        [self.datePickerToolbar setItems:[[NSArray alloc] initWithObjects:extraSpace, doneButton, nil]];
        self.inputView = self.datePicker;
        self.inputAccessoryView = self.datePickerToolbar;
    }
    return self;
}

@end
4

2 回答 2

2

如果您在 storyboard/xib 中添加文本字段,init则不会调用该方法。

尝试使用awakeFromNib. 将init方法中的所有代码移动到awakeFromNib

    - (void)awakeFromNib
{
    [super awakeFromNib];

   self.datePicker = [[UIDatePicker alloc] init];
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    self.datePickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.superview.bounds.size.width, 44)];
    [self.datePickerToolbar setBarStyle:UIBarStyleBlackTranslucent];
    UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(setDatePickerValue:)];
    [self.datePickerToolbar setItems:[[NSArray alloc] initWithObjects:extraSpace, doneButton, nil]];
    self.inputView = self.datePicker;
    self.inputAccessoryView = self.datePickerToolbar;

}
于 2013-11-04T16:01:57.423 回答
0

而不是使用 a UITextField,你为什么不使用 a UIButton。它在未来节省了大量时间。在这种情况下,其UIButton行为类似于带有轻击手势识别器的 UILabel。

但是,如果您需要使用UITextField,请执行以下操作:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:yourTextField])
    {

        // Present the picker here first 
           ...

        // And then...    
        return NO;
    }

    return YES;
}

哦,另外,不要在任何方法中初始化任何子UIView类属性。-initWith...这将触发不匹配的视图生命周期。初始化/访问内部的这些属性-viewDidLoad

于 2013-11-04T15:59:43.347 回答