Last active
January 2, 2021 16:14
-
-
Save KrisRJack/70ffff03a1f42c770b3158bd57e294e9 to your computer and use it in GitHub Desktop.
An easy approach to defining a Blur View in Swift
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
// | |
// BlurView.swift | |
// Created by Kristopher Jackson. | |
// | |
class BlurView: UIView { | |
// Can set style of blur after initialization | |
var style: UIBlurEffect.Style { | |
get { | |
return self.effectStyle | |
} | |
set { | |
self.effectStyle = newValue | |
self.blurView.removeFromSuperview() | |
self.createBlurView(withStyle: newValue) | |
self.addSubview(self.blurView) | |
} | |
} | |
private var blurView: UIVisualEffectView! | |
private var effectStyle: UIBlurEffect.Style! | |
override init(frame: CGRect) { | |
super.init(frame: .zero) | |
self.setUp(withStyle: .dark) | |
} | |
required init(style: UIBlurEffect.Style = .dark) { | |
super.init(frame: .zero) | |
self.setUp(withStyle: style) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
self.setUp(withStyle: .dark) | |
} | |
private func setUp(withStyle style: UIBlurEffect.Style) { | |
self.effectStyle = style | |
self.backgroundColor = .clear | |
self.createBlurView(withStyle: style) | |
self.addSubview(self.blurView) | |
} | |
private func createBlurView(withStyle style: UIBlurEffect.Style) { | |
let blurEffect = UIBlurEffect(style: style) | |
let view = UIVisualEffectView(effect: blurEffect) | |
view.frame.origin = .zero | |
view.frame.size = self.frame.size | |
view.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
self.blurView = view | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment