0

I am trying to create a custom UIVIew-based display box for my app in the form of a "badge" with a title "My name is..." and an empty gray area underneath. I am using Swift with UIKit to draw out the badge which is made up of a UIView with gray background and a UILabel with white text & blue background as a subview of the UIView - here is a screenshot from Xcode:

enter image description here

If I run this in Xcode, the basic "badge" looks like this:

enter image description here

The next thing I want to do is add rounded edges to the UIView with the following code in viewDidLoad() which results in the following image:

// Add rounded edges to all four corners
badgeView.layer.cornerRadius = 20
badgeView.clipsToBounds = true

enter image description here

If I then comment out the above code, and can then add the below code then I am able to add shadows to my badge successfully:

// Apply shadow
badgeView.layer.shadowColor = UIColor.black.cgColor
badgeView.layer.shadowRadius = 5.0
badgeView.layer.shadowOpacity = 1.0
badgeView.layer.shadowOffset = CGSize(width: 1, height: 1)
badgeView.layer.masksToBounds = false

enter image description here

However, when I try to use code to do both - have rounded edges and shadow at the same time - I get the following incorrect result:

enter image description here

The problem I am facing is that the top-left and top-right corners are not rounded. Only the bottom-left and bottom-right corners are rounded. I am able to have rounded corners when there is no shadows, and I am able to have shadows when there is no rounded corners. But I want to have both enabled concurrently so that my "badge" has rounded corners and shadows.

How can I solve this problem?

atrdeveloper
  • 137
  • 8
  • 1
    @HangarRash - Good news! Looks like the following comment in the thread you shared solved the issue specifically for me: https://stackoverflow.com/a/34984063/13558133 (the code snippet related to "Problem 1" in the link fixes the problem). The solution is to have a transparent background as a base UIView for the shadows, then add a subview UIView with border + rounded corners and then add another UIView subview for the content you want clipped by the rounded corners. Now it works! Cheers. – atrdeveloper Mar 06 '23 at 05:46

0 Answers0