I have a UIButton that I'm giving a blurred and darkened background. When I highlight it (press it but don't release on-button), however, it loses its transparency by what seems to be non-transparent layers being added.
Here's a video of it; the problem starts a few seconds in: https://i.sstatic.net/xgZwY.jpg
My custom button class looks like this:
override func layoutSubviews() {
super.layoutSubviews()
let blur = UIVisualEffectView(effect: UIBlurEffect(style: .regular))
blur.frame = self.bounds
blur.isUserInteractionEnabled = false
self.insertSubview(blur, at: 0)
}
Building with: Swift 4, iOS 12 beta
What is the problem here and what's the best way to fix it?
layoutSubviews() is called multiple times, including when the button is highlighted. Consequently, the blur is added each time. I added logic to prevent this, fixing the problem. New code:
var isBlurred = false
override func layoutSubviews() {
super.layoutSubviews()
if !isBlurred {
let blur = UIVisualEffectView(effect: UIBlurEffect(style:
.regular))
blur.frame = self.bounds
blur.isUserInteractionEnabled = false
self.insertSubview(blur, at: 0)
isBlurred = true
}
}
It's a little quick-and-dirty, but it fixes the issue.