ios的UIDatePicker控件在默認情況下,通常在豎屏模式下會顯示得很好,但是在橫屏模式下就會出現錯位得情況。
要解決該問題可以在對應得視圖控制器中加入下面得代碼:
- - (void) viewDidLoad {
- [super viewDidLoad];
- for (UIView * subview in datePicker.subviews) {
- subview.frame = datePicker.bounds;
- }
- }
然後在測試顯示就不會錯位了,如下:
比未作任何處理之前好多了,至少可以正常的顯示了,實際上我們做的操作就是改變了datapicker的frame屬性。
因此,我們可以完成一個可以旋轉的UIDatePicker的子類來讓UIDatePicker支持橫屏和豎屏,代碼如下:
RotatingDatePicker.h
RotatingDatePicker.m
現在,當要創建UIDatePicker或者使用ib來做界面事就都可以直接使用RotatingDatePicke來讓UIDatePicker支持旋轉。
還有一個問題就是UIDatePicker在橫屏模式下並不會橫向完全填充,但是我們可以通過代碼手動將其修正。
- - (void) arrangeViews: (UIInterfaceOrientation)orientation {
- if (UIInterfaceOrientationIsPortrait(orientation)) {
- datePicker.frame = CGRectMake(0, 0, 320, 216);
- }
- else {
- datePicker.frame = CGRectMake(0, 0, 480, 162);
- }
- }
- - (void) viewWillAppear:(BOOL)animated {
- [super viewWillAppear: animated];
- [self arrangeViews:
- [UIApplication sharedApplication].statusBarOrientation];
- }
- - (void) willAnimateRotationToInterfaceOrientation:
- (UIInterfaceOrientation)interfaceOrientation
- duration: (NSTimeInterval)duration {
- [super willAnimateRotationToInterfaceOrientation: interfaceOrientation
- duration: duration];
- [self arrangeViews: interfaceOrientation];
- }
通過上面的代碼,使得在旋轉時根據UIInterfaceOrientation方向
重新設置frame屬性,使得在橫屏模式下只顯示三行信息,如下下圖所示:
參考連接:http://www.llamagraphics.com/developer/using-uidatepicker-landscape-mode