ViewExtensions.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // ViewExtensions.swift
  3. // Sirani
  4. //
  5. // Created by Anhar Solehudin on 30/03/19.
  6. // Copyright © 2019 Anhar Solehudin. All rights reserved.
  7. //
  8. import UIKit
  9. extension UIView {
  10. // show / hide view
  11. func show() {
  12. isHidden = false
  13. }
  14. func hide() {
  15. isHidden = true
  16. }
  17. // add auto layout contraints on view
  18. func anchor(top: NSLayoutYAxisAnchor?, bottom: NSLayoutYAxisAnchor?,
  19. leading: NSLayoutXAxisAnchor?, trailing: NSLayoutXAxisAnchor?,
  20. padding: UIEdgeInsets = .zero, size: CGSize = .zero) {
  21. translatesAutoresizingMaskIntoConstraints = false
  22. if size.width > 0 {
  23. widthAnchor.constraint(equalToConstant: size.width).isActive = true
  24. }
  25. if size.height > 0 {
  26. heightAnchor.constraint(equalToConstant: size.height).isActive = true
  27. }
  28. if let top = top {
  29. topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
  30. }
  31. if let bottom = bottom {
  32. bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true
  33. }
  34. if let leading = leading {
  35. leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
  36. }
  37. if let trailing = trailing {
  38. trailingAnchor.constraint(equalTo: trailing, constant: -padding.right).isActive = true
  39. }
  40. }
  41. // rotate view
  42. func rotate(_ toValue: CGFloat, duration: CFTimeInterval = 0.3) {
  43. let animation = CABasicAnimation(keyPath: "transform.rotation")
  44. animation.toValue = toValue
  45. animation.duration = duration
  46. animation.isRemovedOnCompletion = false
  47. animation.fillMode = CAMediaTimingFillMode.forwards
  48. self.layer.add(animation, forKey: nil)
  49. }
  50. }