Disable orientation for Keyboard in iPhone

2019-01-20 06:27发布

问题:

I need to support only Portrait mode for Keyboard view.

Because, I have an UIViewController that supports all orientations. It presents an View controller which supports only Portrait orientation and this view has an Text Field. When TextField becomes first responder Keyboard view is poped up. Now, if I change the device orientation, keyboard changes its orientation to Landscape.

How do I keep the keyboard in Portrait orientation?

回答1:

Try this:

Create an iVar called UIInterfaceOrientation previousOrientation.

When you say [textField becomeFirstResponder]; add:

[viewController shouldAutoRotateToInterfaceOrientation:UIInterfaceOrientationPortrait];

// Set the previousOrientation to whatever it was
previousOrientation = viewController.interfaceOrientation

// This prevents it from leaving portrait orientation
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

Then in [textField resignFirstResponder], when the user closes the keyboard or presses enter; You can revert to the original orientation.

[ViewController shouldAutoRotateToInterfaceOrientation:previousOrientation];

// Turn the notifications back on so that it will be able to rotate again
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];


回答2:

If you just need Portrait Orientation u can disable Autorotation with:

[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];