I want to achieve a shadow on UITextField
with round corners like below image:
My Code as below:
override func viewDidLoad() {
super.viewDidLoad()
textField.layer.cornerRadius = textField.frame.size.height / 2
textField.layer.borderWidth = 1.0
textField.layer.borderColor = UIColor(white: 0.5, alpha: 0.3).cgColor
textField.layer.shadowOpacity = 1
textField.layer.shadowRadius = 4.0
textField.layer.shadowColor = UIColor.black.cgColor
}
but, I think something is missing...
Output:
thanks in advance!
Try below code to achieve shadow effect on roundRect
textfield.
//Basic texfield Setup
textField.borderStyle = .none
textField.backgroundColor = UIColor.groupTableViewBackground // Use anycolor that give you a 2d look.
//To apply corner radius
textField.layer.cornerRadius = textField.frame.size.height / 2
//To apply border
textField.layer.borderWidth = 0.25
textField.layer.borderColor = UIColor.white.cgColor
//To apply Shadow
textField.layer.shadowOpacity = 1
textField.layer.shadowRadius = 3.0
textField.layer.shadowOffset = CGSize.zero // Use any CGSize
textField.layer.shadowColor = UIColor.gray.cgColor
//To apply padding
let paddingView : UIView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: textField.frame.height))
textField.leftView = paddingView
textField.leftViewMode = UITextFieldViewMode.always
Note: For some reason textField.borderStyle = .none
not taking effect even setting the code in viewWillLayoutSubviews()
or viewDidLayoutSubviews()
.So, I recommend you to set borderStyle through storyBoard textfield Attributes inspector
.
Output from real device:
To achieve a drop shadow effect:(like other SO
posts)
textField.layer.borderColor = UIColor.black.withAlphaComponent(0.25).cgColor
textField.layer.shadowOffset = CGSize(width: 0, height: 3)
textField.layer.shadowColor = UIColor.black.cgColor //Any dark color
Output:
Use this below code
textfield.layer.cornerRadius = textfield.frame.size.height/2
textfield.clipsToBounds = false
textfield.layer.shadowOpacity=0.4
textfield.layer.shadowOffset = CGSize(width: 0, height: 0)
OutPut:
You can add this extension and then use the method "addShadow" to add shadow to you Textfield, label, textview and etc...
extension UIView {
func addShadow(shadowColor: CGColor = UIColor.black.cgColor,
shadowOffset: CGSize = CGSize(width: 1.0, height: 2.0),
shadowOpacity: Float = 0.4,
shadowRadius: CGFloat = 3.0) {
layer.shadowColor = shadowColor
layer.shadowOffset = shadowOffset
layer.shadowOpacity = shadowOpacity
layer.shadowRadius = shadowRadius
layer.masksToBounds = false
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With