Ответ 1
Используйте метод [[UIDevice currentDevice] orientation]
, как указано здесь.
У меня есть приложение с панелью вкладок и контроллерами навигации на каждой вкладке. Когда пользователь встряхивает устройство, в навигационном контроллере отображается дочерний вид UIImageView
. Но UIImageView
должен содержать специальное изображение, в зависимости от текущей ориентации устройства.
Если я пишу только
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)
if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
//Code
}
else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight||interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
//Code
}
}
Взгляд просто сумасшедший, если пользователь повернул устройство перед тем, как встряхнуть.
Есть ли способ получить текущую ориентацию iPhone?
Используйте метод [[UIDevice currentDevice] orientation]
, как указано здесь.
Вот макросы UIDeviceOrientationIsLandscape
и UIDeviceOrientationIsPortrait
поэтому достаточно проверить отдельно, вы можете сделать это вот так...
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
// code for landscape orientation
}
ИЛИ
if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
{
// code for Portrait orientation
}
Как сказал Бено, это кажется лучшим ответом, если вы обнаруживаете ориентацию на ранней стадии своего представления. Я не мог получить одобренный ответ, чтобы вернуть результат в начале моей установки, но это работает чудесно.
if (UIDeviceOrientationIsPortrait(self.interfaceOrientation)){
//DO Portrait
}else{
//DO Landscape
}
Чтобы добавить к уже ответившему вопросу:
Вы используете [[UIDevice currentDevice] orientation]
, который даст одно из следующих значений:
typedef enum {
UIDeviceOrientationUnknown,
UIDeviceOrientationPortrait,
UIDeviceOrientationPortraitUpsideDown,
UIDeviceOrientationLandscapeLeft,
UIDeviceOrientationLandscapeRight,
UIDeviceOrientationFaceUp,
UIDeviceOrientationFaceDown
} UIDeviceOrientation;
Документацию можно найти здесь - (ориентация) и здесь - (UIDeviceOrientation).
(Я не хочу требовать прежнего андерсера, но эта информация была большой для комментария.)
Попробуйте это:
[[UIApplication sharedApplication] statusBarOrientation]
Или в Swift 3:
UIApplication.shared.statusBarOrientation
Чтобы проверить конкретную ориентацию, вы также можете использовать свойство isLandscape
или isPortrait
следующим образом:
UIApplication.shared.statusBarOrientation.isLandscape
Проблема с [[UIDevice currentDevice] orientation]
заключается в том, что он также возвращает UIInterfaceOrientationUnknown
, а statusBarOrientation
- нет.
Существует также свойство UIViewController
interfaceOrientation
, но оно устарело в iOS 8, поэтому не рекомендуется.
Вы проверяете документацию для statusBarOrientation
здесь
Вы также можете использовать свойство interfaceOrientation класса UIViewController, если вы застряли и постоянно получаете UIDeviceOrientationUnknown из UIDevice.
Там хорошо видно, почему [[UIDevice currentdevice] ориентация] может иногда терпеть неудачу: http://bynomial.com/blog/?p=25, особенно если вы хотите обнаружить (например, если вы хотите проверить, когда приложение выходит из фона).
Это поможет вам...
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft || [[UIDevice currentDevice] orientation ]== UIDeviceOrientationLandscapeRight)
{
NSLog(@"Lanscapse");
}
if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown )
{
NSLog(@"UIDeviceOrientationPortrait");
}
}
Вы также можете определить константы, чтобы заработать время:
#define LANDSCAPE UIInterfaceOrientationIsLandscape(self.interfaceOrientation)
#define LANDSCAPE_RIGHT [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft
#define LANDSCAPE_LEFT [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight
#define PORTRAIT UIInterfaceOrientationIsPortrait(self.interfaceOrientation)
#define PORTRAIT_REVERSE [UIDevice currentDevice].orientation == UIDeviceOrientationPortraitUpsideDown
Как простое решение Swift 4.2
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
switch UIDevice.current.orientation{
case .portrait:
print("Portrait")
case .portraitUpsideDown:
print("PortraitUpsideDown")
case .landscapeLeft:
print("LandscapeLeft")
case .landscapeRight:
print("LandscapeRight")
default:
print("Another")
}
}
Вы можете проверить это так (Swift 3):
var isPortrait: Bool {
let orientation = UIDevice.current.orientation
switch orientation {
case .portrait, .portraitUpsideDown:
return true
case .faceUp, .faceDown:
// Check the interface orientation
let interfaceOrientation = UIApplication.shared.statusBarOrientation
switch interfaceOrientation{
case .portrait, .portraitUpsideDown:
return true
default:
return false
}
default: // .unknown
return false // not very satisfying to return false as if we were in landscape :-/
}
}
Если вы находитесь в ViewController, вы также можете сделать это так (именно это я и сделал):
private var isPortrait: Bool {
let orientation = UIDevice.current.orientation
switch orientation {
case .portrait, .portraitUpsideDown:
return true
case .landscapeLeft, .landscapeRight:
return false
default: // unknown or faceUp or FaceDown
return self.view.width < self.view.height
}
}
Хотя даже этого должно быть достаточно в этом случае:
private var isPortrait: Bool {
return self.view.width < self.view.height
}
Обновив его до iOS 8+, где UIViewController.interfaceOrienation
устарела, вы должны использовать traitCollections
. Так, например, чтобы проверить ландшафт на iPhone, вы должны использовать:
if self.traitCollection.verticalSizeClass == .compact
{
your code
}
Обратите внимание, что на iPad это не так, потому что на iPad в альбомной ориентации класс размера не compact
.
Ссылка на Apple Doc
Получение текущей ориентации
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationLandscapeLeft) {
NSLog(@"Landscape left");
self.lblInfo.text = @"Landscape left";
} else if (orientation == UIInterfaceOrientationLandscapeRight) {
NSLog(@"Landscape right");
self.lblInfo.text = @"Landscape right";
} else if (orientation == UIInterfaceOrientationPortrait) {
NSLog(@"Portrait");
self.lblInfo.text = @"Portrait";
} else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
NSLog(@"Upside down");
self.lblInfo.text = @"Upside down";
}
}
И если вы просто хотите, чтобы устройство было в горизонтальной или вертикальной ориентации, простое решение (в Swift):
var orientation = "portrait"
if UIScreen.main.bounds.size.width > UIScreen.main.bounds.size.height {
orientation = "landscape"
}