Swift에서 장치 방향 가져 오기
Swift에서 현재 장치 방향을 어떻게 얻을 수 있는지 궁금합니다. Objective-C에 대한 예제가 있음을 알고 있지만 Swift에서 작동하지 못했습니다.
장치 방향을 가져 와서 if 문에 넣으려고합니다.
이것은 내가 가장 많은 문제를 겪고있는 라인입니다.
[[UIApplication sharedApplication] statusBarOrientation]
당신이 사용할 수있는:
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 : 방향 변경을 감지하는 방법?
참고 : didRotateFromInterfaceOrientation 은 더 이상 사용되지 않습니다. iOS 2.0 이상에서는 viewWillTransitionToSize 사용
Objective-C 코드와 같은 상태 표시 줄 (및 UI) 방향을 얻으려면 다음과 같이하면됩니다.
UIApplication.sharedApplication().statusBarOrientation
UIDevice 의 orientation속성 을 사용할 수도 있습니다 .
UIDevice.currentDevice().orientation
그러나 이는 UI의 방향과 일치하지 않을 수 있습니다. 문서에서 :
속성 값은 장치의 현재 방향을 나타내는 상수입니다. 이 값은 기기의 물리적 방향을 나타내며 애플리케이션 사용자 인터페이스의 현재 방향과 다를 수 있습니다. 가능한 값에 대한 설명은“UIDeviceOrientation”을 참조하십시오.
Apple은 최근에 Landscape vs. Portrait라는 개념을 없애고 화면 크기를 선호합니다. 그러나 이것은 작동합니다.
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
print("landscape")
} else {
print("portrait")
}
}
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. 모든 종류의 뷰 컨트롤러에서 작동합니다.
2. 사용자가 앱을 회전 할 때도 작동합니다.
3. 또한 처음으로 앱을 설치하십시오.
현재 장치 방향을 찾으려면 다음 코드를 사용하십시오.
UIApplication.sharedApplication (). statusBarOrientation
신속한 3.0
UIApplication.shared.statusBarOrientation
스위프트 4 :
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
print("landscape")
} else {
print("portrait")
}
}
So, if Apple is deprecating the whole orientation string thing ("portrait","landscape"), then all you care about is the ratio of width to height. (kinda like @bpedit's answer)
When you divide the width by the height, if the result is less than 1, then the mainScreen or container or whatever is in "portrait" "mode". If the result is greater than 1, it's a "landscape" painting. ;)
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")
}
}
(I'm guessing that if you use this approach then you probably don't really care about specifically handling the condition when the ratio is exactly 1, equal width and height.)
I had issues with using InterfaceOrientation, it worked OK except it wasn't accessing the orientation on loading. So I tried this and it's a keeper. This works because the bounds.width is always in reference to the current orientation as opposed to nativeBounds.width which is absolute.
if UIScreen.mainScreen().bounds.height > UIScreen.mainScreen().bounds.width {
// do your portrait stuff
} else { // in landscape
// do your landscape stuff
}
I call this from willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) and from viewDidLoad but it flexible.
Thanks to zSprawl for the pointer in that direction. I should point out that this is only good for iOS 8 and later.
Swift 3+
Basically:
NotificationCenter.default.addObserver(self, selector: #selector(self.didOrientationChange(_:)), name: .UIDeviceOrientationDidChange, object: nil)
@objc func didOrientationChange(_ notification: Notification) {
//const_pickerBottom.constant = 394
print("other")
switch UIDevice.current.orientation {
case .landscapeLeft, .landscapeRight:
print("landscape")
case .portrait, .portraitUpsideDown:
print("portrait")
default:
print("other")
}
}
:)
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
if (toInterfaceOrientation.isLandscape) {
NSLog("Landscape");
}
else {
NSLog("Portrait");
}
}
Swift 3, based on Rob's answer
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if (size.width / size.height > 1) {
print("landscape")
} else {
print("portrait")
}
}
I found that the alternative code in Swift for the Obj-C code
if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
is
if UIApplication.shared.statusBarOrientation.isLandscape
Note: we are trying to find the status bar orientation is landscape or not. If it is landscape then the if statement is true.
참고URL : https://stackoverflow.com/questions/25796545/getting-device-orientation-in-swift
'Program Club' 카테고리의 다른 글
| 정적 방법과 비 정적 방법의 차이점은 무엇입니까? (0) | 2020.11.12 |
|---|---|
| 시간 개체에 분 추가 (0) | 2020.11.12 |
| 매개 변수가있는 신속한 GET 요청 (0) | 2020.11.12 |
| iOS Swift에서 원을 어떻게 그리나요? (0) | 2020.11.12 |
| C #에서 html을 구문 분석하는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.12 |