如何safeAreaInsets集成到当前的约束扩展

问题描述:

我创建扩展视图的限制。你可以在下面找到代码,但在新版iPhone X之后,我们需要使用safeAreaInsets,但是我不知道如何实现该属性。如果你能帮助我,我会很高兴。如何safeAreaInsets集成到当前的约束扩展

感谢

extension UIView { 

    func anchor (top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat) { 
     translatesAutoresizingMaskIntoConstraints = false 

     if let top = top { 
      self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true 
     } 
     if let left = left { 
      self.leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true 
     } 
     if let right = right { 
      rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true 
     } 
     if let bottom = bottom { 
      bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true 
     } 
     if height != 0 { 
      heightAnchor.constraint(equalToConstant: height).isActive = true 
     } 
     if width != 0 { 
      widthAnchor.constraint(equalToConstant: width).isActive = true 
     } 

    } 

} 

我已经重构你的代码考虑到插图。请尝试以下操作:

import UIKit 

extension UIView { 

    func anchor (top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat, enableInsets: Bool) { 
     var topInset = CGFloat(0) 
     var bottomInset = CGFloat(0) 
     var rightInset = CGFloat(0) 
     var leftInset = CGFloat(0) 

     if #available(iOS 11, *), enableInsets { 
      let insets = self.safeAreaInsets 
      topInset = insets.top 
      bottomInset = insets.bottom 
      rightInset = insets.right 
      leftInset = insets.left 
     } 

     translatesAutoresizingMaskIntoConstraints = false 

     if let top = top { 
      self.topAnchor.constraint(equalTo: top, constant: paddingTop+topInset).isActive = true 
     } 
     if let left = left { 
      self.leftAnchor.constraint(equalTo: left, constant: paddingLeft+leftInset).isActive = true 
     } 
     if let right = right { 
      rightAnchor.constraint(equalTo: right, constant: -paddingRight-rightInset).isActive = true 
     } 
     if let bottom = bottom { 
      bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom-bottomInset).isActive = true 
     } 
     if height != 0 { 
      heightAnchor.constraint(equalToConstant: height).isActive = true 
     } 
     if width != 0 { 
      widthAnchor.constraint(equalToConstant: width).isActive = true 
     } 

    } 

} 
+0

我尝试实施,你写的代码,但没有奏效topInset值始终返回0.0 –

+0

是否设置在iOS的封闭11断点? –

+0

你是否在你的vc的根视图上调用扩展方法? –