Custom Rounding corners on UIView

So I've been stuck on this one for awhile, read and tried many different solutions online, but can't figure out what I'm doing wrong. What I'm trying to accomplish should be very simple: I have a UIView and I want to round its bottom left and right corners so that they are clipped and not drawn.

This is what I have so far (vwView is my outlet for a custom view on screen):

var layerTest = CAShapeLayer()

var bzPath = UIBezierPath(roundedRect: vwView.bounds, byRoundingCorners: [.BottomLeft, .BottomRight], cornerRadii: CGSizeMake(10, 10) )
layerTest.path = bzPath.CGPath

vwView.layer.mask = layerTest;

What am I doing wrong? ALSO: This is just my prototype because I really want to do this on a UITableViewCell, so if there is a different approach I need to take for that, that could also be helpful.

Thanks

James


Solution 1:

The problem is that vwView gets resized later to fit the screen, but you don't update the path for its new size. There's no particularly trivial fix for this. You basically need to make vwView a custom class (if it's not already) and update the mask in layoutSubviews. Example:

public class RoundedBorderView: UIView {

    public var roundedCorners: UIRectCorner = [ .BottomLeft, .BottomRight ] {
        didSet { self.setNeedsLayout() }
    }

    public var cornerRadii: CGSize = CGSizeMake(10, 10) {
        didSet { self.setNeedsLayout() }
    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        updateMask()
    }

    private func updateMask() {
        let mask = maskShapeLayer()
        mask.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundedCorners, cornerRadii: cornerRadii).CGPath
    }

    private func maskShapeLayer() -> CAShapeLayer {
        if let mask = layer.mask as? CAShapeLayer {
            return mask
        }
        let mask = CAShapeLayer()
        layer.mask = mask
        return mask
    }

}

Change the class of vwView to RoundedBorderView and it will maintain its own mask layer.