Uitextfield 背景颜色模糊?

Uitextfield background color blurry?

我正在尝试使 UItextfield 的背景颜色模糊。当我尝试下面的代码时,我的应用程序在运行时崩溃了。有没有人以前试过这个并且知道如何使 UITextfield 模糊?

    let p = UITextField()
    let blurEffect = UIBlurEffect(style: .light)
    let blurView = UIVisualEffectView(effect: blurEffect)
    p.layer.isOpaque = true
    p.layer.backgroundColor = blurView as! CGColor

我找到了一个解决方案,您可以在 UITextfield 后面放置一个视图,并使其透明。

let v = UIView()
v.frame = CGRect(x: 30, y: 100, width: 180, height: 30)
let blurEffect = UIBlurEffect(style: .light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = v.bounds
blurView.backgroundColor = .clear
v.addSubview(blurView)

let p = UITextField()
p.frame = CGRect(x: 0, y: 0, width: 180, height: 30)
p.layer.isOpaque = true
p.backgroundColor = .clear
v.addSubview(p)

self.view.backgroundColor = .red
self.view.addSubview(v)

这是一个 example 建议的解决方案,背景图像不是红色,以强调模糊效果

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background") ?? UIImage())