Swift3检测设备是否为iPad Portrait模式

检测设备方向变化,API变化真快,讨论热烈.

http://stackoverflow.com/questions/25666269/ios8-swift-how-to-detect-orientation-change

起因是在看appcoda的那本iOS 10的书,有个练习是在ipad(portrait)模式下修改某个stack view的spacing从10变成30.

看了一下,好像ipad不管怎么摆size classes都是wR/hR,所以不能通过interface builder修改,只能通过写代码的方式.

最终的我的代码如下(AppDelegate.swift):

func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
   // Override point for customization after application launch.
   NotificationCenter.default.addObserver(self,selector: #selector(rotated),name: NSNotification.Name.UIDeviceOrientationDidChange,object: nil)
   
   return true
}
    
func rotated() {
   let isIPad = UIDevice.current.userInterfaceIdiom == .pad
   let isPortrait = UIDeviceOrientationIsPortrait(UIDevice.current.orientation)
   print("isIPad: \(isIPad),iPortrait: \(isPortrait)")
   
   if isIPad {
       let controller = window!.rootViewController as! ViewController
       controller.myStackView.spacing = isPortrait ? 30.0 : 10.0
   }
}

参考:

  1. http://stackoverflow.com/questions/25666269/ios8-swift-how-to-detect-orientation-change
  2. iOS Apprentice 5th edition
  3. Beginning iOS programming with Swift

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...