Last active
December 24, 2021 00:17
-
-
Save kyungpyoda/5b415498ebfceb77397eabdbf302741e to your computer and use it in GitHub Desktop.
[iOS] Youtube Community ImageView clone
This file contains hidden or 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
// | |
// YoutubeImageView.swift | |
// | |
// Created by 홍경표 on 2021/07/19. | |
// | |
import UIKit | |
class YoutubeImageView: UIImageView { | |
private var isFit: Bool = true { | |
didSet { | |
guard contentMode == .scaleAspectFit || contentMode == .scaleAspectFill | |
else { return } | |
contentMode = isFit ? .scaleAspectFit : .scaleAspectFill | |
} | |
} | |
private let highlightView: UIView = { | |
let highlightView = UIView() | |
highlightView.backgroundColor = .label | |
highlightView.autoresizingMask = [.flexibleHeight, .flexibleWidth] | |
highlightView.alpha = 0 | |
return highlightView | |
}() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
setUp() | |
} | |
override init(image: UIImage?) { | |
super.init(image: image) | |
setUp() | |
} | |
override init(image: UIImage?, highlightedImage: UIImage?) { | |
super.init(image: image, highlightedImage: highlightedImage) | |
setUp() | |
} | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
setUp() | |
} | |
private func setUp() { | |
backgroundColor = .systemGray6 | |
contentMode = .scaleAspectFit | |
layer.masksToBounds = true | |
highlightView.frame.size = frame.size | |
addSubview(highlightView) | |
isUserInteractionEnabled = true | |
let tap = UILongPressGestureRecognizer(target: self, action: #selector(tapHandler)) | |
tap.minimumPressDuration = 0 | |
tap.delegate = self | |
addGestureRecognizer(tap) | |
} | |
@objc private func tapHandler(gesture: UITapGestureRecognizer) { | |
if gesture.state == .ended { | |
isFit.toggle() | |
} else if gesture.state != .began { | |
gesture.isEnabled = false | |
gesture.isEnabled = true | |
} | |
highlightView.alpha = gesture.state == .began ? 0.1 : 0 | |
} | |
} | |
extension YoutubeImageView: UIGestureRecognizerDelegate { | |
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, | |
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { | |
return true | |
} | |
} |
Author
kyungpyoda
commented
Jul 26, 2021
- 탭 할 때마다 contentMode가 AspectToFit <-> AspectToFill 전환
- 탭한 상태로 스크롤하면 취소
Original(Youtube Community) | My Clone |
---|---|
![]() |
![]() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment