I am having issue with constraints. I am using UIBezierPath and auto layout. I have done almost everything given here and still the issue is not rectified and that is why I am posting this question. I am using the following function for rounding certain corner of my view (which I have made using storyboard)
func addShadowAndCorner(shadowColor: UIColor, offSet: CGSize, opacity: Float, shadowRadius: CGFloat, cornerRadius: CGFloat, corners: UIRectCorner, fillColor: UIColor = .white) {
let shadowLayer = CAShapeLayer()
let size = CGSize(width: cornerRadius, height: cornerRadius)
let cgPath = UIBezierPath(roundedRect: self.curvedView.bounds, byRoundingCorners: corners, cornerRadii: size).cgPath //1
shadowLayer.path = cgPath //2
shadowLayer.fillColor = fillColor.cgColor //3
shadowLayer.shadowColor = shadowColor.cgColor //4
shadowLayer.shadowPath = cgPath
shadowLayer.shadowOffset = offSet //5
shadowLayer.shadowOpacity = opacity
shadowLayer.shadowRadius = shadowRadius
self.curvedView.layer.addSublayer(shadowLayer)
}
Then I am calling this function as below
func configureView() {
self.view.backgroundColor = UIColor(named: "appBackgroundColor")
curvedView.backgroundColor = .clear
self.addShadowAndCorner(shadowColor: .darkGray, offSet: CGSize.init(width: 3.0, height: 3.0), opacity: 0.6, shadowRadius: 8, cornerRadius: 80, corners: [.topRight, .bottomLeft], fillColor: .white)
}
I have called the above function inside "override func viewDidLayoutSubviews()". But I am not getting expected behaviours for constraints on different phone sizes
The code works well when running on iPhone 11 simulator, the screenshot is shared below.
But when running the same code on iPhone SE simulator it is not working as expected. The screenshot is shared below for iPhone SE
The constraints for curvedView in storyboard is.
Please help me here. Thanks in advance
2
Answers
You should apply the shadow code in didLayoutSubviews. At that point your views know their frame sizes. Make sure you call super too.
Be careful not to re-add the shadow sublayer every time by just calling your addShadowAndCorner function from didLayoutSubviews.
You’ll have the most reliable (and flexible) results by creating a custom
UIView
subclass.Here’s a quick example:
You can then add a
UIView
in Storyboard, assign its Custom Class toMyCustomView
, connect it to an@IBOutlet
, and then inviewDidLoad()
:Now, it will auto-update itself when its frame changes… such as on different devices or on device rotation:
You can create it via code like this:
and, with very little effort, you can make it
@IBDesignable
and configure your properties as@IBInspectable
… then you can visually see the result when you lay it out in Storyboard.The only tricky property is the Corners, because there is no direct
@IBInspectable
option forUIRectCorner
… so we can use Bool properties for each corner:Now, we get this in Storyboard: