Get safe area inset top and bottom heights

后端 未结 15 1429
长发绾君心
长发绾君心 2020-11-30 17:30

On the new iPhone X, what would be the most proper way to get both top and bottom height for the unsafe areas?

15条回答
  •  执念已碎
    2020-11-30 17:41

    A more rounded approach

      import SnapKit
    
      let containerView = UIView()
      containerView.backgroundColor = .red
      self.view.addSubview(containerView)
      containerView.snp.remakeConstraints { (make) -> Void in
            make.width.top.equalToSuperView()
            make.top.equalTo(self.view.safeArea.top)
            make.bottom.equalTo(self.view.safeArea.bottom)
      }
    
    
    
    
    extension UIView {
        var safeArea: ConstraintBasicAttributesDSL {
            if #available(iOS 11.0, *) {
                return self.safeAreaLayoutGuide.snp
            }
            return self.snp
        }
    
    
        var isIphoneX: Bool {
    
            if #available(iOS 11.0, *) {
                if topSafeAreaInset > CGFloat(0) {
                    return true
                } else {
                    return false
                }
            } else {
                return false
            }
    
        }
    
        var topSafeAreaInset: CGFloat {
            let window = UIApplication.shared.keyWindow
            var topPadding: CGFloat = 0
            if #available(iOS 11.0, *) {
                topPadding = window?.safeAreaInsets.top ?? 0
            }
    
            return topPadding
        }
    
        var bottomSafeAreaInset: CGFloat {
            let window = UIApplication.shared.keyWindow
            var bottomPadding: CGFloat = 0
            if #available(iOS 11.0, *) {
                bottomPadding = window?.safeAreaInsets.bottom ?? 0
            }
    
            return bottomPadding
        }
    }
    

提交回复
热议问题