Created
March 8, 2022 07:16
-
-
Save kyungpyoda/23a7c4de1bc0465662d613c802f6e942 to your computer and use it in GitHub Desktop.
[iOS, Swift] Add touch highlight effect to UIView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIView+addHighlightEffect.swift | |
// | |
// | |
// Created by 홍경표 on 2021/11/17. | |
// | |
import UIKit | |
public extension UIView { | |
func addHighlightEffect(highlightColor: UIColor = .c013) { | |
let highlightView = HighlightView(color: highlightColor) | |
self.addSubview(highlightView) | |
highlightView.snp.makeConstraints { $0.edges.equalToSuperview() } | |
self.bringSubviewToFront(highlightView) | |
} | |
} | |
open class HighlightView: UIView { | |
private let highlightColor: UIColor | |
public init(color: UIColor = .systemGray5) { | |
self.highlightColor = color | |
super.init(frame: .zero) | |
self.backgroundColor = .clear | |
self.alpha = 0.5 | |
} | |
required public init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { | |
DispatchQueue.main.async { | |
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: { | |
self.backgroundColor = self.highlightColor | |
}, completion: nil) | |
} | |
super.touchesBegan(touches, with: event) | |
} | |
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { | |
DispatchQueue.main.async { | |
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut) { | |
self.backgroundColor = .clear | |
} | |
} | |
super.touchesEnded(touches, with: event) | |
} | |
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { | |
DispatchQueue.main.async { | |
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut) { | |
self.backgroundColor = .clear | |
} | |
} | |
super.touchesCancelled(touches, with: event) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment