Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing the corner radius of UITextField removes its shadow

Tags:

ios

swift3

I have a UITextField with custom code to control the corner radius and the placeholder color and another different properties. Also, I have a Protocol with Extension to drop shadow from any UI element.

The problem is: whenever I increase the corner radius of the text field, I lose the shadow. As long as the corner radius is 0, I still have a shadow.

And this shows at the debugger when I increase the cornerRadius and lose the shadow:

setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key height

Here is my Protocol I implemented to drop shadow:

import UIKit

protocol DropShadow {}

extension DropShadow where Self: UIView {

    func addDropShadow() {
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.7
        layer.shadowOffset = CGSize(width: 0, height: 4)
        layer.shadowRadius = 3
    }
}

And here is my custom class for the UITextField:

import UIKit

@IBDesignable
class FancyTextField: UITextField, DropShadow {

    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }

    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet {
            layer.borderColor = borderColor?.cgColor
        }
    }

    @IBInspectable var bgColor: UIColor? {
        didSet {
            backgroundColor = bgColor
        }
    }

    @IBInspectable var placeHolderColor: UIColor? {
        didSet {
            let rawString = attributedPlaceholder?.string != nil ? attributedPlaceholder!.string : ""
            let str = NSAttributedString(string: rawString, attributes: [NSForegroundColorAttributeName: placeHolderColor!])
            attributedPlaceholder = str
        }
    }

}
like image 550
MEnnabah Avatar asked Oct 29 '22 16:10

MEnnabah


1 Answers

When you add a corner radius to a UIView you have to set the clipsToBounds or masksToBounds to be true. That doesn't allow the shadow to be created as the shadow is created outside the bounds.

As a solution for this problem, you will have to create a superView to the UIView that has the clipped corners, and add a shadow to this superView (Make sure to set the superview to clear color)

like image 50
Rikh Avatar answered Nov 14 '22 21:11

Rikh