Apply rounded border and shadow is not working for UITextField

I want to get the following user interface 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 detailing detail,

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

      


How can I solve this problem?

+3


source to share


3 answers


I cannot reproduce case 1 you ran into, so I will post my code that seems to reach the UI you want.

class RoundTextField: UITextField {

    override func layoutSubviews() {
        super.layoutSubviews()
        borderStyle = .none
        layer.cornerRadius = bounds.height / 2
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.init(colorLiteralRed: 241/256, green: 241/256, blue: 241/256, alpha: 1).cgColor
        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 1.0)
        layer.shadowRadius = 2
        layer.masksToBounds = false
        layer.shadowOpacity = 1.0
        // set backgroundColor in order to cover the shadow inside the bounds
        layer.backgroundColor = UIColor.white.cgColor
    }
}

      



This is a screenshot of my simulator: enter image description here I also uploaded the complete project to Dropbox.

+1


source


You must set the layer.masksToBounds parameter to true.



+1


source


Try calling this method from LayoutSubViews.

override func layoutSubviews() {
        super.layoutSubviews()
        // Call here
    }

      

0


source







All Articles