iOS 6:在UITextField中使用UIDatePicker

4

我在连接日期选择器和文本框方面遇到了问题。我尝试了stackoverflow上的所有解决方案,但它们在iOS 6上不起作用。你能描述一下如何制作它吗?我想通过日期选择器在文本框中选择日期。

2个回答

2
您应该使用UITextFieldinputView属性,以使选择器显示在键盘的位置。然后,iOS6会自动处理一切(用动画显示选择器而不是键盘等)。
注意:您可能还需要添加一些inputAccessoryView(通常是一个带有“确定”按钮的UIToolBar),以使用户能够关闭选择器(当然,您“确定”按钮的IBAction将简单地调用[textField resignFirstResponder])。因为UIDatePicker没有任何验证输入的按钮(而键盘有其“Return Key”)。

-2
#import "TextfieldwithDatepickerViewController.h"

UIActionSheet *pickerViewPopup;

@implementation TextfieldwithDatepickerViewController
- (void)textFieldDidBeginEditing:(UITextField *)aTextField{  
    [aTextField resignFirstResponder];  

    pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];  

    UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];  
    pickerView.datePickerMode = UIDatePickerModeDate;  
    pickerView.hidden = NO;  
    pickerView.date = [NSDate date];  

    UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];  
    pickerToolbar.barStyle = UIBarStyleBlackOpaque;  
    [pickerToolbar sizeToFit];  

    NSMutableArray *barItems = [[NSMutableArray alloc] init];  

    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];  
    [barItems addObject:flexSpace];  

    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];  
    [barItems addObject:doneBtn];  

    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];  
    [barItems addObject:cancelBtn];  

    [pickerToolbar setItems:barItems animated:YES];  

    [pickerViewPopup addSubview:pickerToolbar];  
    [pickerViewPopup addSubview:pickerView];  
    [pickerViewPopup showInView:self.view];  
    [pickerViewPopup setBounds:CGRectMake(0,0,320, 464)];  
}  

-(void)doneButtonPressed:(id)sender{  
    //Do something here here with the value selected using [pickerView date] to get that value  

    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];  
}  

-(void)cancelButtonPressed:(id)sender{  
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];  
}  

我已经创建并编译了代码,也成功启动了应用程序,但选择视图(pickview)或选择工具栏(picktoolbar)未在界面中出现。只有标准键盘显示出来了。您能否提供带有日期选择器的项目源代码?或者您可以将其上传至GitHub吗? - alterpub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接