Is it possible to have both CornerRaduis and a shadow on a UIView?
I set up a Custom class for a UIView which uses @IBInspectable to set a cornerRadius and a addShadow which can be true or false. When I set the cornerRadius the shadow doesn't display, if I take away the cornerRadius then it displays again. Thanks in advance!
Custom class:
import UIKit
class CustomUIView: UIView {
override func awakeFromNib() {
self.layer.masksToBounds = cornerRadius > 0
}
@IBInspectable var useDefaultRadius: Bool = true {
didSet {
self.layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
self.layer.cornerRadius = newValue
}
get {
if (useDefaultRadius) {
// Set default radius
self.layer.cornerRadius = 23
}
return self.layer.cornerRadius
}
}
@IBInspectable var addShadow:Bool = true{
didSet(newValue) {
if(newValue == true){
self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = CGSize(width: 2, height: 3)
self.layer.shadowRadius = 3
self.layer.shadowPath = UIBezierPath(rect: bounds).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
print("trying to use shadow")
}
}
}
}
Rather than creating custom clas and changing class of uiview everytime, i prefer extending it. I'm achieving this by extending UIView as mentioned below:
And set properties in storyboard as:
That's it.
Hope this helps.