需求是這樣的:在畫面上點擊 textfield 時,不要彈出虛擬鍵盤、也不要 datepicker 或 actionsheet,而是顯示一個類似網頁日曆輸入框的自訂日曆視圖。
這類元件網路上有不少開源方案,但未必符合需求,因此參考 Kal 的思路自己實作了一個。日曆視圖以自訂 view 的方式呈現,add 到 view controller 的 view 上,最後透過日曆視圖的 delegate 把自身移除。
關鍵是讓 textFieldShouldBeginEditing 回傳 NO(阻止系統鍵盤彈出),改由我們自己顯示日曆:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
GTMLoggerDebug(@"textField tag is %d", textField.tag);
[self testCalView];
return NO;
}
- (void)testCalView
{
// 以系統 NSCalendar 取得日期資料
self.logicDao = [[XYCalendarDao alloc] initForDate:[NSDate date]];
calView = [[XYCalView alloc] initWithFrame:self.view.frame logicDao:self.logicDao];
calView.delegate = self;
// 以 CATransition 加入由上方推入的轉場動畫
CATransition *transition = [CATransition animation];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromTop;
transition.duration = 0.6f;
transition.fillMode = kCAFillModeForwards;
transition.removedOnCompletion = YES;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[calView.layer addAnimation:transition forKey:@"transition"];
[self.view addSubview:calView];
}
- (void)slideOutCalView:(XYCalDate *)selectedDate
{
// 以 UIView 動畫讓日曆滑出畫面
[UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
calView.frame = CGRectMake(0, calView.frame.size.height,
calView.frame.size.width, calView.frame.size.height);
} completion:^(BOOL finished) {
[calView removeFromSuperview];
}];
// 將所選日期格式化後填入 textfield
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *strDate = [dateFormatter stringFromDate:[selectedDate NSDate]];
self.testCalendar.text = strDate;
}
本文示範了兩種動畫寫法:打開時用 CATransition(推入轉場),關閉時用 UIView 的 animation block(位移滑出)。搭配自訂的日曆 view 與 delegate 回傳,就能打造一個不喚起系統鍵盤的日期選擇體驗。