//注意:要获取safeAreaInsets最好的办法是重写viewSafeAreaInsetsDidChange函数,在里面获取。因为viewDidLoad之前,safeAreaInsets是0值。并且屏幕也会转动。 override func viewSafeAreaInsetsDidChange () { print(view.safeAreaInsets.bottom) } //这里以safeAreaInsets举例建立类似宏定义的东西 //全局的 //建一个.swift文件 //创建常量 let SafeAreaInsets = UIEdgeInsets(top: 44, left: 0, bottom: 34, right: 0) //view.safeAreaInsets要在viewDidLoad之后调用才有正确的值,所以可以写一个全局常量,默认lazy属性,延时加载只赋值一次 //注意,常量只会赋值一次,竖屏调用后,转横屏,再调用值不会变 let SafeAreaInsets: UIEdgeInsets = { guard #available(iOS 11.0, *), let safeAreaInsets = UIApplication.shared.delegate?.window??.safeAreaInsets else { return UIEdgeInsets() } return safeAreaInsets } () //本页的 //如果常量很多且是类似的,可以在本页面建一个私有结构体,定义静态常量和方法 private struct Constants { //静态常量 static let SafeAreaInsets = UIEdgeInsets(top: 44, left: 0, bottom: 34, right: 0) static func safeAreaInsets () -> UIEdgeInsets { guard #available(iOS 11.0, *), let safeAreaInsets = UIApplication.shared.delegate?.window??.safeAreaInsets else { return UIEdgeInsets() } return safeAreaInsets } } //调用 print(Constants.SafeAreaInsets, Constants.safeAreaInsets())