IOS開發-顯示DatePicker當敲擊textfield – iPhone手機開發技術文章 iPhone軟體開發教學課程

最近做項目遇到一個問題,在一個設置頁面有兩個輸入框,想讓用戶敲擊時,彈出日期控件,選擇日期時間。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

 

You May Also Like