0

I have labels that I want to round the corners of in Swift, the labels are created in the Xcode storyboard. The solution I was using at first was:

label.layer.masksToBounds = true
label.layer.cornerRadius = 8.0

Though with this solution, it rounds all corners instead of just the top left and bottom left.

I looked around Stackoverflow, and came up with the following solution to round only the top left and bottom left corners:

let bounds: CGRect = label.bounds
let maskPath = UIBezierPath(roundedRect: bounds, 
    byRoundingCorners: ([.topLeft, .bottomLeft]), 
    cornerRadii: CGSize(width: 8.0, height: 8.0))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
label.layer.mask = maskLayer

I have also attempted to enable maskToBounds here, with no result.

Now this solution works for only rounding the two corners that I want to round, though the label no longer follows the constraints I was using for the UI unlike with the first solution which worked with my UI constraints.

For layout I am using stack views, to stack the label with a button next to it horizontally, and then each pair is placed in a vertical stack view to stack four pairs on top of each other. After making the change to the second solution, the label now cuts off short of the button next to it that it is supposed to match in height.

First solution:

First solution

Second solution:

Second Solution

I'd appreciate a detailed answer as I am relatively new to Swift and am interested in learning what the issue is.

maldahleh
  • 313
  • 3
  • 18
  • 1
    If you are using autolayout, you shouldn't mess with the frame – Skywalker Nov 24 '17 at 02:08
  • @Skywalker so if I wanted to apply rounded corners to a label would it have to be added in programatically as opposed to through the Storyboard? – maldahleh Nov 24 '17 at 02:10
  • Did you enable masksToBounds in second solution? – Lumialxk Nov 24 '17 at 02:13
  • @Lumialxk yes I did attempt that, sorry forgot to include that in question, will edit question to mention that. – maldahleh Nov 24 '17 at 02:15
  • You need to recalculate the mask when the view bounds change. Add an override to `viewDidLayoutSubviews` to your view controller. – Gary Makin Nov 24 '17 at 02:15
  • @GaryMakin Okay thanks, tried to look around to see how it's done, would you be able to explain how to recalculate the mask or at least point me in a direction to look for it? – maldahleh Nov 24 '17 at 02:22
  • 1
    https://stackoverflow.com/questions/2504151/calayers-didnt-get-resized-on-its-uiviews-bounds-change-why might give you the hints you need. Unfortunately, I don't have time to write this up right now. – Gary Makin Nov 24 '17 at 02:48
  • @GaryMakin thanks your comment with the link helped me :) – Lance Samaria Mar 11 '20 at 15:04

0 Answers0