2017-09-26 25 views
0

ビューの制約の拡張を作成しました。あなたは以下のコードを見つけることができますが、新しいリリースの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 
     } 

    } 

} 

答えて

1

は私がインセットを考慮に入れるためにあなたのコードをリファクタリングしています。試してみてください次:

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

私はあなたが書いたコードを実装しようとしていますがiOSの11の閉鎖にブレークポイントを設定していることがtopInset値が常に0.0 –

+0

を返す動作しませんでしたか? –

+0

あなたのVCのルートビューで拡張メソッドを呼び出していますか? –

関連する問題