ios的UIDatePicker控件在默认情况下,通常在竖屏模式下会显示得很好,但是在横屏模式下就会出现错位得情况。
要解决该问题可以在对应得视图控制器中加入下面得代码:
- (void) viewDidLoad { [super viewDidLoad]; for (UIView * subview in datePicker.subviews) { subview.frame = datePicker.bounds; } }然后在测试显示就不会错位了,如下:
比未作任何处理之前好多了,至少可以正常的显示了,实际上我们做的操作就是改变了datapicker的frame属性。
因此,我们可以完成一个可以旋转的UIDatePicker的子类来让UIDatePicker支持横屏和竖屏,代码如下:
#import <UIKit/UIKit.h> @interface RotatingDatePicker : UIDatePicker { } @end
#import "RotatingDatePicker.h" @implementation RotatingDatePicker - (id)initWithFrame: (CGRect)frame { if (self = [super initWithFrame:frame]) { for (UIView * subview in self.subviews) { subview.frame = self.bounds; } } return self; } - (id) initWithCoder: (NSCoder *)aDecoder { if (self = [super initWithCoder: aDecoder]) { for (UIView * subview in self.subviews) { subview.frame = self.bounds; } } return self; } @end
现在,当要创建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属性,使得在横屏模式下只显示三行信息,如下下图所示: