nunzio giulio caggegi nunzio giulio caggegi - 1 month ago 11
iOS Question

Swift UITextField Border bottom and shadow issues

I have a UITextField that must have a bottom border. Since autolayout use my code is this:

override func viewDidLayoutSubviews() {
let border = CALayer()
let width = CGFloat(0.5)
border.borderColor = UIColor.darkGray.withAlphaComponent(0.3).cgColor
border.frame = CGRect(x: 0, y: txtUsername.frame.size.height - width, width: txtUsername.frame.size.width, height: txtUsername.frame.size.height)

border.borderWidth = width
txtUsername.layer.addSublayer(border)
txtUsername.layer.masksToBounds = true
}


This, however, excludes the fact that when I touch the UITextField, this should create me a shadow. the code is this:

//ombra txtField
self.view.addSubview(txtUsername)
txtUsername.layer.shadowOffset = CGSize(width: 5, height: 10)
txtUsername.layer.shadowOpacity = 0.3
txtUsername.layer.shadowRadius = 10
txtUsername.layer.masksToBounds = false;
txtUsername.clipsToBounds = false


the one excludes the other. how do I fix?`

Answer

You can use CAShapeLayerShadow

func border(){
let border = CALayer()
    let width = CGFloat(0.5)
    border.borderColor = UIColor.darkGray.withAlphaComponent(1).cgColor
    border.frame = CGRect(x: 0, y: CustomerTextBox.frame.size.height - width, width:  CustomerTextBox.frame.size.width, height: CustomerTextBox.frame.size.height)

    border.borderWidth = width
    CustomerTextBox.layer.addSublayer(border)
    CustomerTextBox.layer.masksToBounds = true

  }


   func shadow(){
    let Shape = CAShapeLayer()
     let myPath = UIBezierPath(ovalIn: CustomerTextBox.frame)

    Shape.shadowPath = myPath.cgPath
    Shape.shadowColor = UIColor.lightGray.cgColor
    Shape.shadowOffset = CGSize(width: 5, height: 3)
    Shape.shadowRadius  = 5
    Shape.shadowOpacity = 0.8


    view.layer.insertSublayer(Shape, at: 0)

   }

enter image description here

Comments