最近做專案時遇到一個需求:設定頁面有兩個輸入框,希望使用者點擊時能彈出日期選擇器來挑選日期與時間。上網找了一圈,發現很少有完整可用的方案,這裡把 Solve 的過程整理出來分享。
思路其實很乾淨:UITextField 有兩個很適用的屬性——inputView 與 inputAccessoryView。把 UIDatePicker 指定給 textField 的 inputView,鍵盤位置就會變成日期選擇器;再建立一個含「Done」按鈕的 UIToolbar 指定給 inputAccessoryView,就能用這個 Done 鈕收起選擇器。
按下 Done 時,要讓目前處於編輯狀態的輸入框結束回應:
if ([textField1 isFirstResponder]) {
[textField1 resignFirstResponder];
} else if ([textField2 isFirstResponder]) {
[textField2 resignFirstResponder];
}
先在介面(XIB)中拖出一個 UIToolbar 與一個 UIDatePicker,注意不要把它們附加到 view 上(拖到視圖外面即可),再適當連接 outlets:
@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
其中 dateChanged: 回應 datePicker 的 Value Changed,doneEditing: 則由工具列上的 Done 按鈕觸發(在 Connection → Sent Actions 中連接)。實作如下:
@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;
...
return YES;
}
- (IBAction)dateChanged:(id)sender {
UIDatePicker *picker = (UIDatePicker *)sender;
self.textField.text = [NSString stringWithFormat:@"%@", picker.date];
}
- (IBAction)doneEditing:(id)sender {
[self.textField resignFirstResponder];
}
@end
透過這套寫法,使用者點擊輸入框時會直接彈出日期選擇器,選好後按 Done 即可收起,操作起來與原生體驗相當一致。若想推廣到多個輸入框,只要為每個 textField 各自指定 inputView 與 accessoryView,並在 Done 邏輯中判斷目前是哪一個處於 first responder 即可。