Apply rounded border as well as shadow doesn't work for UITextField

Viewed 1257

I want to achieve the following UI
enter image description here

And here is my code for it

class RoundTextField: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        customize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        customize()
    }

    func customize() {
        apply(shadow: true)
    }

    func apply(shadow: Bool) {
        if shadow {
            borderStyle = .none
            layer.cornerRadius = bounds.height / 2

            layer.borderWidth = 1.0
            layer.borderColor = UIColor.lightGray.cgColor
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOffset = CGSize(width: 0, height: 5.0)
            layer.shadowRadius = 2
            layer.masksToBounds = false
            layer.shadowOpacity = 1.0
        } else {

        }
    }
}

And here is the issue detail,

  • Case 1: For the above code I get a textField without any border or shadow,
  • Case 2: If I comment the first two lines, I get the shadow effect with the border is not rounded, and the border gets to default rounded border.
borderStyle = .none
layer.cornerRadius = bounds.height / 2


How could I resolve this issue ?

3 Answers
Related