您的位置:首页 > 移动开发 > IOS开发

IOS开发-显示DatePicker当敲击textfield

2012-12-24 16:27 344 查看
最近做项目遇到一个问题,在一个设置页面有两个输入框,想让用户敲击时,弹出日期控件,选择日期时间。Baidu了一遍,发现没有一个完整的解决方案,现在解决了,分享一下。

你可以用textfield的inputview和inputAccessoryView两个属性。创建datePicker,赋值给两个textfield的inputview属性。创建toolbar,包含一个Done按钮,赋值给inputAccessoryView属性。你需要用这个Done来退出inputview。

Done的事件处理:

if ( [textField1 isFirstResponder] ) {
[textField1 resignFirstResponder];
} else if ( [textField2 isFirstResponder] ) {
[textField2 resignFirstResponder];
}

Example

@interface 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


正在学习过程中,错误之处请指正,欢迎交流,共同学习;
Demo:http://download.csdn.net/detail/xdrt81y/5858521
欢迎转载分享,请注明出处http://blog.csdn.net/xdrt81y
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: