2014-09-11 2 views
41

Swift에서 현재 장치 방향을 어떻게 얻을 수 있는지 궁금합니다. Objective-C에 대한 예제가 있지만 Swift에서 작동시키지 못했습니다.Swift에서 장치 방향 얻기

장치 방향을 가져 와서 if 문에 넣으려고합니다. 단순히, 당신이 가지고있는 목표 - C 코드와 같은 상태 표시 줄 (및 그 UI) 방향을 얻으려면

[[UIApplication sharedApplication] statusBarOrientation] 
+0

무엇 당신의 문제? 이를 Swift로 번역하거나 기대하는 가치를 얻으시겠습니까? –

+0

장치 방향이 사용자의 UI 방향과 일치하지 않을 수 있습니다. 케이싱 포인트 - 장치를 평평하게 놓고 코드를 테스트하십시오! – Patrick

답변

33

:

내가 가진 가장 문제가 오전 라인
UIApplication.sharedApplication().statusBarOrientation 

또한 UIDevice의 orientation property 사용할 수 없습니다 :

UIDevice.currentDevice().orientation 

을 그러나, 더 할 수있다 귀하의 UI가 어떤 방향으로 일치하는지 확인하십시오. 문서에서 :

이 속성의 값은 현재 장치의 방향을 나타내는 상수입니다. 이 값은 실제 기기의 방향을 나타내며 현재 애플리케이션의 사용자 인터페이스 방향 인 과 다를 수 있습니다. 가능한 값에 대한 설명은 "UIDeviceOrientation"을 참조하십시오.

47

당신은 사용할 수 있습니다

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { 
    var text="" 
    switch UIDevice.currentDevice().orientation{ 
    case .Portrait: 
     text="Portrait" 
    case .PortraitUpsideDown: 
     text="PortraitUpsideDown" 
    case .LandscapeLeft: 
     text="LandscapeLeft" 
    case .LandscapeRight: 
     text="LandscapeRight" 
    default: 
     text="Another" 
    } 
    NSLog("You have moved: \(text)")   
} 

SWIFT 3 업데이트 알림과

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { 
    var text="" 
    switch UIDevice.current.orientation{ 
    case .portrait: 
     text="Portrait" 
    case .portraitUpsideDown: 
     text="PortraitUpsideDown" 
    case .landscapeLeft: 
     text="LandscapeLeft" 
    case .landscapeRight: 
     text="LandscapeRight" 
    default: 
     text="Another" 
    } 
    NSLog("You have moved: \(text)")   
} 

또는

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { 
} 

당신이 확인할 수 있습니다 IOS8 Swift: How to detect orientation change?

참고 :didRotateFromInterfaceOrientation은 아이폰 OS 2.0을 사용 viewWillTransitionToSize를 더 이상 사용되지 않으며 이후

16

애플이 최근 세로 대 가로의 아이디어를 제거있어 우리는 화면 크기를 사용하여 선호한다. 그러나,이 작품 : 그것은로드의 방향을 액세스하고 있지 것을 제외하고

내가 InterfaceOrientation를 사용하여 문제를했다
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { 
    if UIDevice.currentDevice().orientation.isLandscape.boolValue { 
     print("landscape") 
    } else { 
     print("portrait") 
    } 
} 
+4

귀하의 솔루션에 사과로 표시됩니다. "사용자 정의보기 컨트롤러에서이 메서드를 무시하면 구현의 어느 시점에서 항상 super를 호출합니다." – Popmedic

2
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { 
    if (toInterfaceOrientation.isLandscape) { 
     NSLog("Landscape"); 
    } 
    else { 
     NSLog("Portrait"); 
    } 
} 
7

, 그것은 확인했다. 그래서 나는 이것을 시도했고 그것은 골키퍼 다. 이는 bounds.width이 절대 방향 인 nativeBounds.width이 아닌 현재 방향을 항상 참조하기 때문에 효과가 있습니다.

if UIScreen.mainScreen().bounds.height > UIScreen.mainScreen().bounds.width { 
     // do your portrait stuff 
    } else { // in landscape 
     // do your landscape stuff 
    } 

나는 willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval)에서와 viewDidLoad에서이 전화를하지만 유연한.

포인터를 해당 방향으로 zSprawl 해준 덕분입니다. iOS 8 이상에서만 유효하다는 점을 지적해야합니다.

+0

은 iOS 9 및 10 iPads에서 작동하지 않으며 초기 값만 정확합니다. 다음의 모든 값은 반대 방향입니다. –

+0

@ Steven.B Hmmm ... iOS 9 이하의 iPad Air, iPad 3 및 시뮬레이터에서 잘 작동합니다. 베타 테스터와도 작업했습니다. 아마도이 문제에 영향을 미치는 다른 코드를 사용하고있을 수도 있습니다. – bpedit

+0

이 코드는 UIViewcontroller에서 사용할 때만 작동합니다. 사용자 지정 UIView 클래스에서 방향 및 경계를 가져 오려고하지만 거의 모든 장치가 다른 값을 반환합니다. 방향이 프레임보다 정확하거나 경계가 여전히 잘못되었을 때 . –

6

그래서 Apple이 전체 오리엔테이션 문자열 ("portrait", "landscape")을 사용하지 않으려한다면, 너는 높이와 너비의 비율 만 신경 쓰면됩니다. (일종의 @ bpedit의 답변)

너비를 높이로 나누면 결과가 1보다 작 으면 주 화면이나 컨테이너 또는 "세로" "모드"가됩니다. 결과가 1보다 크면 "풍경"그림입니다. ;)

override func viewWillAppear(animated: Bool) { 
    let size: CGSize = UIScreen.mainScreen().bounds.size 
    if size.width/size.height > 1 { 
     print("landscape") 
    } else { 
     print("portrait") 
    } 
} 
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { 
    if size.width/size.height > 1 { 
     print("landscape") 
    } else { 
     print("portrait") 
    } 
} 

(난 당신이 다음이 방법을 사용하는 경우 당신은 아마 정말 비율이 정확히 1, 동일한 폭과 높이를 때 조건 처리에 대한 특별히 걱정하지 않는다 같은데요)

10

. 단순히이 코드를 사용하여 현재 장치 방향을 찾는 방법은 다음과 같습니다.

UIApplication.sharedApplication()를 statusBarOrientation

을 신속 3.0

UIApplication.shared.statusBarOrientation

+0

iPad 공기 1 및 2가 잘못된 값을 반환합니다. iPad 2 및 iPhone이 정확합니다. 나는 정말로 모든 장치에서 작동하는 하나를 찾으려고 노력하고 있지만, 사과는 여기서 진짜 혼란을 일으켰습니다! : (UIDevice.current.orientation','UIApplication.shared '와는 달리 –

+0

.statusBarOrientation'은 화면이 회전 된 후에가 아니라 초기로드에서 사용할 수 있습니다. – ewizard

2

스위프트 롭의 답변에 따라 3,

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { 
    if (size.width/size.height > 1) { 
     print("landscape") 
    } else { 
     print("portrait") 
    } 
} 
6
struct DeviceInfo { 
struct Orientation { 
    // indicate current device is in the LandScape orientation 
    static var isLandscape: Bool { 
     get { 
      return UIDevice.current.orientation.isValidInterfaceOrientation 
       ? UIDevice.current.orientation.isLandscape 
       : UIApplication.shared.statusBarOrientation.isLandscape 
     } 
    } 
    // indicate current device is in the Portrait orientation 
    static var isPortrait: Bool { 
     get { 
      return UIDevice.current.orientation.isValidInterfaceOrientation 
       ? UIDevice.current.orientation.isPortrait 
       : UIApplication.shared.statusBarOrientation.isPortrait 
     } 
    } 
}} 

swift4의 대답이 내가 그것을 어떻게 ,

모든 일에 대한 1. works 뷰 컨트롤러의 DS

2.also 작업은 사용자가 응용 프로그램을 처음 설치할 때의 응용 프로그램

3.also에게

+0

완벽하게 신속하게 작동합니다. 감사합니다 –

+0

완벽한 답변! 감사 – torap

2

스위프트 4 회전 할 때 :

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { 
     if UIDevice.current.orientation.isLandscape { 
      print("landscape") 
     } else { 
      print("portrait") 
     } 
    }