【问题标题】:How to globally detect device active orientation changes outside of a swift-file?如何全局检测 swift 文件之外的设备活动方向变化?
【发布时间】:2018-12-29 03:54:08
【问题描述】:

我无法弄清楚如何在计算器视图控制器中更新圆角半径(请参阅本文末尾链接中的图像)。我正在使用 viewWillLayoutSubviews() 设置角半径,到目前为止它运行良好。但是,我注意到,如果我从计算器视图控制器屏幕过渡,旋转设备,然后导航回计算器视图控制器屏幕,角半径仍然基于之前的方向屏幕。我尝试在 viewDidAppear() 中调用 viewWillLayoutSubviews(),但是在正确设置按钮角半径之前存在明显的延迟。

如何判断设备方向是否在库或其他视图控制器中发生变化?导航回计算器屏幕时,我需要能够加载圆形按钮。感谢您抽出宝贵的时间,感谢您提供的任何意见。感谢您的宝贵时间!

Screenshots of my current application from loading screen to the point of the corner radius not being updated correctly

【问题讨论】:

    标签: swift orientation rounded-corners cornerradius


    【解决方案1】:

    您可以在 viewdidLoad 中添加以下代码以检查设备方向

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

    现在每次来时检查设备方向并根据下面的代码重新加载您的视图

    - (void) orientationChanged:(NSNotification *)note { }
    

    【讨论】:

      【解决方案2】:

      将此代码添加到您的应用委托。因此,您知道设备是全局处于横向还是纵向模式。然后你可以使用 Viewwill 来改变半径。

      import UIKit
      
      
      @UIApplicationMain
      class AppDelegate: UIResponder, UIApplicationDelegate {
      
      var window: UIWindow?
      
      var didRotate: (Notification) -> Void = { notification in
          switch UIDevice.current.orientation {
          case .landscapeLeft, .landscapeRight:
              print("landscape")
          case .portrait, .portraitUpsideDown:
              print("Portrait")
          default:
              print("other")
          }
      }
      
      
      
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
          // Override point for customization after application launch.
      
          NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification,
                                                 object: nil,
                                                 queue: .main,
                                                 using: didRotate)
      
      
          return true
      }
      
      }
      

      【讨论】:

      • 我收到以下错误:“使用未声明的类型'UNUserNotificationCenterDelegate'”
      • 现在就来看看吧!谢谢!
      • 好的。已在设备上对其进行了测试以检查其是否有效。如果对您有用,请标记为正确。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      相关资源
      最近更新 更多