橫屏模式(landscape)下的UIDatePicker

 ios的UIDatePicker控件在默認情況下,通常在豎屏模式下會顯示得很好,但是在橫屏模式下就會出現錯位得情況。

要解決該問題可以在對應得視圖控制器中加入下面得代碼:

  1. - (void) viewDidLoad { 
  2.     [super viewDidLoad]; 
  3.     for (UIView * subview in datePicker.subviews) { 
  4.         subview.frame = datePicker.bounds; 
  5.     } 

然後在測試顯示就不會錯位了,如下:

比未作任何處理之前好多了,至少可以正常的顯示了,實際上我們做的操作就是改變了datapicker的frame屬性。

因此,我們可以完成一個可以旋轉的UIDatePicker的子類來讓UIDatePicker支持橫屏和豎屏,代碼如下:

RotatingDatePicker.h

  1. #import <UIKit/UIKit.h> 
  2. @interface RotatingDatePicker : UIDatePicker { 
  3. @end 

RotatingDatePicker.m

  1. #import "RotatingDatePicker.h" 
  2.  
  3. @implementation RotatingDatePicker 
  4.  
  5. - (id)initWithFrame: (CGRect)frame { 
  6.     if (self = [super initWithFrame:frame]) { 
  7.         for (UIView * subview in self.subviews) { 
  8.             subview.frame = self.bounds; 
  9.         } 
  10.     } 
  11.     return self; 
  12.  
  13. - (id) initWithCoder: (NSCoder *)aDecoder { 
  14.     if (self = [super initWithCoder: aDecoder]) { 
  15.         for (UIView * subview in self.subviews) { 
  16.             subview.frame = self.bounds; 
  17.         } 
  18.     } 
  19.     return self; 
  20.  
  21. @end 

現在,當要創建UIDatePicker或者使用ib來做界面事就都可以直接使用RotatingDatePicke來讓UIDatePicker支持旋轉。

還有一個問題就是UIDatePicker在橫屏模式下並不會橫向完全填充,但是我們可以通過代碼手動將其修正。

  1. - (void) arrangeViews: (UIInterfaceOrientation)orientation { 
  2.     if (UIInterfaceOrientationIsPortrait(orientation)) { 
  3.         datePicker.frame = CGRectMake(0, 0, 320, 216); 
  4.     } 
  5.     else { 
  6.         datePicker.frame = CGRectMake(0, 0, 480, 162); 
  7.     } 
  8.  
  9. - (void) viewWillAppear:(BOOL)animated { 
  10.     [super viewWillAppear: animated]; 
  11.     [self arrangeViews: 
  12.           [UIApplication sharedApplication].statusBarOrientation]; 
  13.  
  14. - (void) willAnimateRotationToInterfaceOrientation: 
  15.                           (UIInterfaceOrientation)interfaceOrientation 
  16.          duration: (NSTimeInterval)duration { 
  17.     [super willAnimateRotationToInterfaceOrientation: interfaceOrientation 
  18.                                             duration: duration]; 
  19.     [self arrangeViews: interfaceOrientation]; 

通過上面的代碼,使得在旋轉時根據UIInterfaceOrientation方向

重新設置frame屬性,使得在橫屏模式下只顯示三行信息,如下下圖所示:

參考連接:http://www.llamagraphics.com/developer/using-uidatepicker-landscape-mode

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章