0

I am trying to make the background color of a UItextfield blurry. When I try the code below, my app crashes when it runs. Has anyone tried this before and knows how to make a UITextfield blurry?

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

1 Answers1

0

I found a solution where you place a view behind the UITextfield, and make it transparent.

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)

This is an example of proposed solution, with background image instead of red color, to emphasize the blur effect

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background") ?? UIImage())
carmine
  • 1,597
  • 2
  • 24
  • 33
  • thank you for your response. I have tried to use your solution but for some reason, it is not working for me. The view simply does not show up. –  Mar 04 '19 at 04:54
  • Which view is not shown? I assume, in my code, that you work in a view controller. I also used fixed values for frame CGRect, but you can place it with autolayout. – carmine Mar 04 '19 at 07:54
  • @Brian look at sample and let me know – carmine Mar 04 '19 at 08:24
  • will this work if the images constantly change? say the blurry view is over a user submitted photo?? will the blurry background show the different photos? –  Mar 05 '19 at 06:19
  • @Brian yes of course. Blurry is just a visual effect and it depends on what is behind the view is applied to. – carmine Mar 05 '19 at 08:24