Last active
November 13, 2024 08:29
-
-
Save mathebox/4b1c8581446c489ecddb898855f3f065 to your computer and use it in GitHub Desktop.
UIView with inner shadow in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class InnerShadowView: UIView { | |
lazy var innerShadowLayer: CAShapeLayer = { | |
let shadowLayer = CAShapeLayer() | |
shadowLayer.shadowColor = UIColor.black.cgColor | |
shadowLayer.shadowOffset = CGSize(width: 0.0, height: 0.0) | |
shadowLayer.shadowOpacity = 0.1 | |
shadowLayer.shadowRadius = 14 | |
shadowLayer.fillRule = .evenOdd | |
return shadowLayer | |
}() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
self.configure() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
self.configure() | |
} | |
private func configure() { | |
self.layer.masksToBounds = true | |
self.layer.cornerRadius = 6 | |
self.layer.addSublayer(self.innerShadowLayer) | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
let shadowPath = CGMutablePath() | |
let inset = -self.innerShadowLayer.shadowRadius * 2.0 | |
shadowPath.addRect(self.bounds.insetBy(dx: inset, dy: inset)) | |
shadowPath.addRect(self.bounds) | |
self.innerShadowLayer.path = shadowPath | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment