Bharath
Bharath

Reputation: 2114

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

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,

borderStyle = .none
layer.cornerRadius = bounds.height / 2


How could I resolve this issue ?

Upvotes: 3

Views: 1311

Answers (3)

Mike Qiu
Mike Qiu

Reputation: 136

I can't reproduce the case 1 you encounter so I will post my code that seems achieve 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 the screenshot of my simulator: enter image description here

Upvotes: 3

Fayez Hellani
Fayez Hellani

Reputation: 101

You should set layer.masksToBounds to true.

Upvotes: 1

Himanshu
Himanshu

Reputation: 2832

Try calling these method from LayoutSubViews instead.

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

Upvotes: 0

Related Questions