xcodeuitextfieldbackground-coloruiblureffect

Uitextfield background color blurry?


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

Solution

  • 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())