IOS开发-显示DatePicker当敲击textfield
最近做项目遇到一个问题,在一个设置页面有两个输入框,想让用户敲击时,弹出日期控件,选择日期时间。Baidu了一遍,发现没有一个完整的解决方案,现在解决了,分享一下。
你可以用textfield的inputview和inputAccessoryView两个属性。创建datePicker,赋值给两个textfield的inputview属性。创建易做图,包含一个Done按钮,赋值给inputAccessoryView属性。你需要用这个Done来退出inputview。
Done的事件处理:
if ( [textField1 isFirstResponder] ) {
[textField1 resignFirstResponder];
} else if ( [textField2 isFirstResponder] ) {
[textField2 resignFirstResponder];
}
Example
@inte易做图ce CustomKeyboardAppDelegate : NSObject <UIApplicationDelegate> {
...
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITextField *textField;
@property (nonatomic, retain) IBOutlet UIToolbar *accessoryView;
@property (nonatomic, retain) IBOutlet UIDatePicker *customInput;
- (IBAction)dateChanged:(id)sender;
- (IBAction)doneEditing:(id)sender;
@end
在XIB文件中,拖出 一个UIToolbar和一个UIDatePicker,但不要附加到View中(拖到视图外面)。适当的连接Outlets。dateChanged:响应datepicker的ValueChanges,doneEditing:被ToolBar中的Done按钮点击时调用(Connection->Sent Actions->selectors)。以下是实现:
@implementation CustomKeyboardAppDelegate
@synthesize window=_window;
@synthesize textField = _textField;
@synthesize accessoryView = _accessoryView;
@synthesize customInput = _customInput;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.textField.inputView = self.customInput;
self.textField.inputAccessoryView = self.accessoryView;
...
}
...
- (IBAction)dateChanged:(id)sender {
UIDatePicker *picker = (UIDatePicker *)sender;
self.textField.text = [NSString stringWithFormat:@"%@", picker.date];
}
- (IBAction)doneEditing:(id)sender {
[self.textField resignFirstResponder];
}
@end
补充:移动开发 , IOS ,