CloseButton.swift 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // CloseButton.swift
  3. // WeScan
  4. //
  5. // Created by Boris Emorine on 2/27/18.
  6. // Copyright © 2018 WeTransfer. All rights reserved.
  7. //
  8. import UIKit
  9. /// A simple close button shaped like an "X".
  10. final class CloseButton: UIControl {
  11. let xLayer = CAShapeLayer()
  12. override init(frame: CGRect) {
  13. super.init(frame: frame)
  14. layer.addSublayer(xLayer)
  15. backgroundColor = .clear
  16. isAccessibilityElement = true
  17. accessibilityTraits = UIAccessibilityTraitButton
  18. }
  19. required init?(coder aDecoder: NSCoder) {
  20. fatalError("init(coder:) has not been implemented")
  21. }
  22. override func draw(_ rect: CGRect) {
  23. self.clipsToBounds = false
  24. xLayer.frame = rect
  25. xLayer.lineWidth = 3.0
  26. xLayer.path = pathForX(inRect: rect.insetBy(dx: xLayer.lineWidth / 2, dy: xLayer.lineWidth / 2)).cgPath
  27. xLayer.fillColor = UIColor.clear.cgColor
  28. xLayer.strokeColor = UIColor.black.cgColor
  29. xLayer.lineCap = kCALineCapRound
  30. }
  31. private func pathForX(inRect rect: CGRect) -> UIBezierPath {
  32. let path = UIBezierPath()
  33. path.move(to: rect.origin)
  34. path.addLine(to: CGPoint(x: rect.origin.x + rect.width, y: rect.origin.y + rect.height))
  35. path.move(to: CGPoint(x: rect.origin.x + rect.width, y: rect.origin.y))
  36. path.addLine(to: CGPoint(x: rect.origin.x, y: rect.origin.y + rect.height))
  37. return path
  38. }
  39. }