如何让按钮背景变得模糊?
我发现用这个模糊了效果:
let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
blur.frame = buttonForDisabling.frame
self.tableView.addSubview(blur)
这是有效的,但只能使用与我的按钮相同的帧进行模糊。我想要一个背景模糊的按钮。在iOS8中可以吗?
答案 0 :(得分:14)
这可以通过创建模糊并将其插入UIButton的titleLabel下方来完成。禁用用户交互非常重要,以便允许触摸不被视觉效果视图截取并转发到按钮。
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)
答案 1 :(得分:13)
如果您使用带图像的按钮,请将图像视图置于前面:
buttonForDisabling.bringSubview(toFront: buttonForDisabling.imageView!)
或只使用此扩展程序:
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)
}
}
}
答案 2 :(得分:1)
使用了Sherwin的great answer,但对我来说并不奏效,因为我使用自动布局,并且在运行此代码时我的框架为.zero。所以我修改了代码以使用自动布局,这现在对我有用:
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)
}
}
}
答案 3 :(得分:0)
@tuvok的出色响应的Swift 5版本。我还对其进行了更新,并添加了控制各个方面的选项,例如:
•style
:模糊样式
•cornerRadius
:允许您将其设置为圆形或圆形
•padding
:如果您想使用cornerRadius,但又想增大按钮的大小以进行点击测试,则该功能很有用。
extension UIButton {
func addBlurEffect(style: UIBlurEffect.Style = .regular, cornerRadius: CGFloat = 0, padding: CGFloat = 0) {
backgroundColor = .clear
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: style))
blurView.frame = bounds.inset(by: UIEdgeInsets(horizontal: padding, vertical: padding))
blurView.isUserInteractionEnabled = false
blurView.backgroundColor = .clear
if cornerRadius > 0 {
blurView.layer.cornerRadius = cornerRadius
blurView.layer.masksToBounds = true
}
self.insertSubview(blurView, at: 0)
if let imageView = self.imageView{
imageView.backgroundColor = .clear
self.bringSubviewToFront(imageView)
}
}
}