How can i make a button background get blurred?
Ill found out to get a blurred effect with this:
let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
blur.frame = buttonForDisabling.frame
self.tableView.addSubview(blur)
This is working, but only makes a blur with the same frame as my button. I would like to have a button with a blurred background. Is that possible in iOS8?
If you are using a button with an image, bring the imageview to front:
buttonForDisabling.bringSubview(toFront: buttonForDisabling.imageView!)
or just use this extension:
import Foundation
import UIKit
extension UIButton
{
func addBlurEffect()
{
let blur = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blur.frame = self.bounds
blur.isUserInteractionEnabled = false
self.insertSubview(blur, at: 0)
if let imageView = self.imageView{
self.bringSubview(toFront: imageView)
}
}
}
This can be done by creating the blur as you did and inserting it below the titleLabel of the UIButton. It's important to disable user interaction in order to allow the touches to not be intercepted by the the visual effect view and forwarded to the button.
Swift 4.2:
let blur = UIVisualEffectView(effect: UIBlurEffect(style:
UIBlurEffect.Style.light))
blur.frame = buttonForDisabling.bounds
blur.isUserInteractionEnabled = false //This allows touches to forward to the button.
buttonForDisabling.insertSubview(blur, at: 0)
Used Sherwin's great answer, but it didn't quite work for me as I use auto layout and my frame was .zero while this code runs. So I modified the code to use auto-layout and this now works for me:
import Foundation
import UIKit
extension UIButton {
func addBlurEffect(style: UIBlurEffect.Style = .regular, cornerRadius: CGFloat = 0, padding: CGFloat = 0) {
backgroundColor = .clear
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: style))
blurView.isUserInteractionEnabled = false
blurView.backgroundColor = .clear
if cornerRadius > 0 {
blurView.layer.cornerRadius = cornerRadius
blurView.layer.masksToBounds = true
}
self.insertSubview(blurView, at: 0)
blurView.translatesAutoresizingMaskIntoConstraints = false
self.leadingAnchor.constraint(equalTo: blurView.leadingAnchor, constant: padding).isActive = true
self.trailingAnchor.constraint(equalTo: blurView.trailingAnchor, constant: -padding).isActive = true
self.topAnchor.constraint(equalTo: blurView.topAnchor, constant: padding).isActive = true
self.bottomAnchor.constraint(equalTo: blurView.bottomAnchor, constant: -padding).isActive = true
if let imageView = self.imageView {
imageView.backgroundColor = .clear
self.bringSubviewToFront(imageView)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With