需求是這樣的:點擊 textField 後,弹出的既不是系統鍵盤,也不是 UIDatePicker,更不是 ActionSheet,而是一個類似網頁日曆控件那樣的月曆面板,用戶直接在上面選日期。
開源社區此類控件不少,但现成的都不完全符合設計稿。於是參考 Kal 的思路,自己實現了一個。整體結構是:日曆以自定義視圖的形式存在,運行時 add 到控制器的 view 上,選完日期後通過 delegate 通知外部把自己移除。
關鍵在 textFieldShouldBeginEditing: 返回 NO,這樣系統鍵盤不會彈出,同時在裡面打開日曆視圖。
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
GTMLoggerDebug(@"textField tag is %d", textField.tag);
[self testCalView];
return NO;
}
日期數據依然來自系統自帶的 NSCalendar,封裝在自定義的 DAO 裡,便於後續擴展節假日、農曆等規則。
- (void)testCalView
{
self.logicDao = [[XYCalendarDao alloc] initForDate:[NSDate date]];
calView = [[XYCalView alloc] initWithFrame:self.view.frame logicDao:self.logicDao];
calView.delegate = self;
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"];
NSLog(@"calView is %@", NSStringFromCGRect(calView.frame));
[self.view addSubview:calView];
}
用戶選好日期後,日曆視圖調用 delegate 把選中的日期回傳,控制器負責播放退場動畫並將其從視圖層移除,最後把格式化後的字符串寫回 textField。
- (void)slideOutCalView:(XYCalDate *)selectedDate
{
[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];
}];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *strDate = [dateFormatter stringFromDate:[selectedDate NSDate]];
self.testCalendar.text = strDate;
}
文中刻意用了兩套動畫:出場用 CATransition,入退場用 UIView animateWithDuration:。前者勝在簡短,一行設置即可完成轉場;後者能直接改 frame,適合跟手勢或需要與其他佈局聯動的場景。兩種方式也可以互相替換,選用哪一種取決於是否需要精確控制每一幀的屬性變化。
實戰中還建議補充幾點:點擊半透明遮罩區域時同樣要能關閉日曆;日曆視圖加鎖前應判斷是否已存在,避免重複 add;以及為 NSDateFormatter 建立單例,這類對象創建成本不低,放在每次回調裡 new 一個並非好習慣。