Skip to content

Instantly share code, notes, and snippets.

@TheImShrey
Last active April 2, 2024 12:52
Show Gist options
  • Save TheImShrey/ba8e28d1a2bb7a46dd583a57272dc964 to your computer and use it in GitHub Desktop.
Save TheImShrey/ba8e28d1a2bb7a46dd583a57272dc964 to your computer and use it in GitHub Desktop.
@BlurredBackground property observer
@propertyWrapper
struct BlurredBackground<Content> where Content: UIView {
var disposeBag = DisposeBag()
private let blurEffectView: UIVisualEffectView
var wrappedValue: Content {
didSet {
self.manageHierarchy()
disposeBag = DisposeBag()
self.trackHierarchy()
}
}
init(wrappedValue: Content, style: UIBlurEffect.Style) {
let blurEffect = UIBlurEffect(style: style)
self.blurEffectView = UIVisualEffectView(effect: blurEffect)
self.wrappedValue = wrappedValue
self.resetHierarchy()
self.trackHierarchy()
}
func resetHierarchy() {
if let superview = wrappedValue.superview {
blurEffectView.cornerRadius = wrappedValue.cornerRadius
if superview != blurEffectView.superview {
blurEffectView.snp.removeConstraints()
superview.insertSubview(blurEffectView, belowSubview: wrappedValue)
blurEffectView.edgesEqual(to: wrappedValue)
}
} else {
blurEffectView.cornerRadius = 0
blurEffectView.snp.removeConstraints()
blurEffectView.removeFromSuperview()
}
}
func trackHierarchy() {
self.wrappedValue.rx.methodInvoked(#selector(UIView.didMoveToSuperview))
.subscribe(onNext: { [self] _ in
/// Notice: No retain cycle`self` as this is struct
self.resetHierarchy()
})
.disposed(by: self.disposeBag)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment