横屏模式(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值