I want to shape a UIView and be able to see its shape in the Interface Builder, when I set the following class to my UIView it fails to build, I'm not sure where's the error.
@IBDesignable
class CircleExampleView: UIView {
override func layoutSubviews() {
setupMask()
}
func setupMask() {
let path = makePath()
// mask the whole view to that shape
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
private func makePath() -> UIBezierPath {
//// Oval Drawing
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 11, y: 12, width: 30, height: 30))
UIColor.gray.setFill()
ovalPath.fill()
return ovalPath
}
}
A couple of observations:
You are calling
setFillfollowed byfill, but you only do that if drawing into a graphics context (e.g., indraw(_:)). When usingCAShapeLayer, you should instead set thefillColorof theCAShapeLayer.You are using the
CAShapeLayerto set the mask of your view. If yourUIViewdoesn't have a discerniblebackgroundColor, you won't see anything.If you set the background color of the view to, say, blue, as shown below, your mask will reveal that blue background wherever the mask allows it to (in the oval of your path).
You have implemented
layoutSubviews. You generally would do that only if you were doing something here that was contingent upon theboundsof the view. For example, here's a rendition where the oval path is based upon theboundsof the view:As E. Coms said, if you override
layoutSubviews, you really should call thesuperimplementation. This isn't critical, as the default implementation actually does nothing, but it's best practice. E.g. if you later changed this class to subclass some otherUIViewsubclass, you don't want to have to go to revisit all these overrides.If you have a designable view, it's advisable to put that in a separate target. That way, the rendering of the view in the storyboard is not dependent upon any work that may be underway in the main project. As long as the designables target (often the name of your main target with
Kitsuffix) can build, the designable view can be rendered.For example, here is a rendition of your designable view, in a separate framework target, and used in a storyboard where the view in question has a blue
backgroundColor:For what it's worth, I think it's exceedingly confusing to have to mask to reveal the background color inside the oval. An app developer has to set "background" color in order to set what's inside the oval, but not the background.
I might instead remove the "mask" logic and instead give the designable view an inspectable property,
fillColor, and just add aCAShapeLayeras a sublayer, using thatfillColor:This accomplishes the same thing, but I think the distinction of fill colors vs background colors is more intuitive. But you may have had other reasons for using the masking approach, but just make sure if you do that, that you have something to reveal after it’s masked (e.g. a background color or something else you’re rendering).