code

iOS UIDevice 방향 감지

codestyles 2020. 11. 3. 08:02
반응형

iOS UIDevice 방향 감지


특수 애니메이션을 발동 할 수 있도록 장치가 세로 방향인지 감지해야합니다. 하지만 내 뷰가 자동으로 회전하는 것을 원하지 않습니다.

장치가 세로로 회전 할 때 자동 회전하는보기를 재정의하려면 어떻게합니까? 내 앱은 가로로만 표시하면되지만 회전을 세로로 감지하려면 세로도 지원해야하는 것 같습니다.


애플리케이션이로드되거나보기가로드 될 때 다음을 수행하십시오.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]
   addObserver:self selector:@selector(orientationChanged:)
   name:UIDeviceOrientationDidChangeNotification
   object:[UIDevice currentDevice]];

그런 다음 다음 방법을 추가하십시오.

- (void) orientationChanged:(NSNotification *)note
{
   UIDevice * device = note.object;
   switch(device.orientation)
   {
       case UIDeviceOrientationPortrait:
       /* start special animation */
       break;

       case UIDeviceOrientationPortraitUpsideDown:
       /* start special animation */
       break;

       default:
       break;
   };
}

위의 방법을 사용하면보기 자동 회전을 활성화하지 않고도 장치의 방향 변경을 등록 할 수 있습니다.


노트

iOS의 모든 경우에 관찰자를 추가 할 때 적절한 시간에 제거합니다 (보기가 나타나거나 사라질 때 항상 그런 것은 아님). 관찰 / 비 관찰 코드의 "쌍"만 가질 수 있습니다. 이렇게하지 않으면 앱이 충돌합니다. 관찰 / 무시할 위치를 선택하는 것은이 QA의 범위를 벗어납니다. 그러나 위의 "observe"코드와 일치하려면 "unobserve"가 있어야합니다.


회전을 비활성화 할 필요없이 방향 변경을 감지하는 방법을 찾고있는이 질문에 올 경우 viewWillTransitionToSizeiOS 8에서 사용할 수있는를 알고 있어야 합니다.

여기 에서 신속한 예

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

    coordinator.animateAlongsideTransition({ (UIViewControllerTransitionCoordinatorContext) -> Void in

        let orient = UIApplication.sharedApplication().statusBarOrientation

        switch orient {
        case .Portrait:
            println("Portrait")
            // Do something
        default:
            println("Anything But Portrait")
            // Do something else
        }

        }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
            println("rotation completed")
    })

    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}

실제 방향에 대해 걱정할 필요가없는 경우 :

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

    // do something

    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}

여기 에서 Objective-C 예제

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{   
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
    {
        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        // do whatever
    } completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
    { 

    }];

    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}

그리고 실제 방향에 대해 걱정할 필요가 없다면 ( 이 답변 에서 가져옴 ) :

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    // Do view manipulation here.
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}

또한보십시오


1) David의 대답의 Swift 버전 2) 방향 변경이 없을 때 방향을 감지하고 싶은 경우 ( iOS에서 장치의 방향어떻게 감지합니까? ) 대한 Moe의 대답의 Swift 버전

    // Initial device orientation
    let orientation: UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
    if(orientation == UIInterfaceOrientation.Unknown){
        // code for Unknown
    }
    else if(orientation == UIInterfaceOrientation.Portrait){
        // code for Portrait
    }
    else if(orientation == UIInterfaceOrientation.PortraitUpsideDown){
        // code for Portrait
    }
    else if(orientation == UIInterfaceOrientation.LandscapeRight){
        // code for Landscape        
    }
    else if(orientation == UIInterfaceOrientation.LandscapeLeft){
        // ode for Landscape
    }

    // To detect device orientation change
    UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "orientationChanged:",
        name: UIDeviceOrientationDidChangeNotification,
        object: UIDevice.currentDevice())

orientationChanged 기능

func orientationChanged(note: NSNotification)
{
    let device: UIDevice = note.object as! UIDevice
    switch(device.orientation)
    {
        case UIDeviceOrientation.Portrait:
        // code for Portrait
        break
        case UIDeviceOrientation.PortraitUpsideDown:
        // code for Portrait
        break
        case UIDeviceOrientation.LandscapeLeft:
        // code for Landscape
        break
        case UIDeviceOrientation.LandscapeRight:
        // code for Landscape
        break
        case UIDeviceOrientation.Unknown:
        // code for Unknown
        break
        default:
        break
    }
}

내가 올바르게 이해한다면 앱은 가로 모드입니다. 앱 설정에서 가로로만 지정하므로 회전에 대해 걱정할 필요가 없습니다. 이 앱은 iPad의 방향에 관계없이 가로 모드로 시작하여 그대로 유지됩니다.


먼저 원하는 방향을 제외하고 모두 비활성화 (회전하지 않도록)

Then like David said just get the device current orientation:

https://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/MotionEvents/MotionEvents.html

Alternatively you can just use the accelerometer yourself (since its how it is done anyway) and check where the gravity is at to see what orientation it has. If you take this approach you can play with the values yourself to get different results.


If you do not want to create device object, you can also use

-(void) seObserverForOrientationChanging
{
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(orientationChanged:)
     name:UIDeviceOrientationDidChangeNotification
     object:[UIDevice currentDevice]];
}


- (void) orientationChanged:(NSNotification *)note
{
    if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
        //Do something in landscape
    }
    else {
        //Do something in portrait
    }
}

.UIDeviceOrientationDidChange notification is called many times on iphone even when device did not rotate. Do not know the reason, but if you need it only when device really rotated, then do the following.

NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: .UIDeviceOrientationDidChange, object: nil)

The method called from observer should look like this:

func orientationChanged() {

    if traitCollection.isIphone {

        defer {
            self.previousTraitCollectionForIphone = traitCollection
        }

        guard let previousTraitCollectionForIphone = previousTraitCollectionForIphone else {

            updateView()
            return
        }

        if previousTraitCollectionForIphone != traitCollection {
            updateView()
        }

    } else {
        updateView()
    }
}

참고URL : https://stackoverflow.com/questions/9122149/detecting-ios-uidevice-orientation

반응형