Advertisement
HXXXXJ

Align views

Mar 18th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.94 KB | None | 0 0
  1.  
  2. extension UIView{
  3.     func align(_ anchor : Anchor, to siblingView: UIView) -> UIView{
  4.         switch anchor {
  5.         case .leading:
  6.             self.frame.origin.x = siblingView.frame.origin.x
  7.         case .trailing:
  8.             self.frame.origin.x = siblingView.frame.origin.x + siblingView.frame.width - self.frame.width
  9.         case .top:
  10.             self.frame.origin.y = siblingView.frame.origin.y
  11.         case .botton:
  12.             self.frame.origin.y = siblingView.frame.origin.y + siblingView.frame.height - self.frame.height
  13.         case .centerX:
  14.             self.center.x = siblingView.center.x
  15.         case .centerY:
  16.             self.center.y = siblingView.center.y
  17.         }
  18.         return self
  19.     }
  20. }
  21.  
  22.  
  23. enum Anchor {
  24.     case leading
  25.     case top
  26.     case botton
  27.     case centerX
  28.     case centerY
  29.     case trailing
  30. }
  31.  
  32.  
  33.  
  34.  
  35. /*
  36.  
  37.  - align view if they are not at same view hierarchy。
  38.  > 总体思路就是 要移动那个, 就把另一个的坐标系变成这个要动的
  39.  ```swift
  40.  */
  41. extension UIView{
  42.    
  43.     func alignWithDifferentCoordinate(_ anchor : Anchor, to siblingView: UIView) -> UIView{
  44.         //move self, so convert siblingView's frame to self's coordinate
  45.         let rect = siblingView.convert(siblingView.bounds, to: self.superview)  //-> 这里siblingView bound 就是siblingView自己把自己当坐标系
  46.         switch anchor {
  47.         case .leading:
  48.             self.frame.origin.x = rect.origin.x
  49.         case .trailing:
  50.             self.frame.origin.x = rect.origin.x + rect.width - self.frame.width
  51.         case .top:
  52.             self.frame.origin.y = rect.origin.y
  53.         case .botton:
  54.             self.frame.origin.y = rect.origin.y + rect.height - self.frame.height
  55.         case .centerX:
  56.             self.center.x = rect.origin.x + rect.width / 2
  57.         case .centerY:
  58.             self.center.y = rect.origin.y + rect.height / 2
  59.         }
  60.        
  61.         return self
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement