Hello I have a request to create a UIView with cornerRadius only on topLeft and topRight and add borderColor only at left, right and top
Searching for an answer I tried some solutions but the best I’ve got is this
As you can see I have the sides I want with borders but they’re not rounded
Here is what I tried:
let firstView = UIView(frame: CGRect(x: 30, y: 60, width: 100, height: 100))
firstView.layer.cornerRadius = 10
firstView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
firstView.backgroundColor = .white
firstView.borders(for: [.top, .left, .right])
This is the code I used searching SO
extension UIView {
func borders(for edges:[UIRectEdge], width:CGFloat = 1, color: UIColor = .black) {
if edges.contains(.all) {
layer.borderWidth = width
layer.borderColor = color.cgColor
} else {
let allSpecificBorders:[UIRectEdge] = [.top, .bottom, .left, .right]
for edge in allSpecificBorders {
if let v = viewWithTag(Int(edge.rawValue)) {
v.removeFromSuperview()
}
if edges.contains(edge) {
let v = UIView()
v.tag = Int(edge.rawValue)
v.backgroundColor = color
v.translatesAutoresizingMaskIntoConstraints = false
addSubview(v)
var horizontalVisualFormat = "H:"
var verticalVisualFormat = "V:"
switch edge {
case UIRectEdge.bottom:
horizontalVisualFormat += "|-(0)-[v]-(0)-|"
verticalVisualFormat += "[v((width))]-(0)-|"
case UIRectEdge.top:
horizontalVisualFormat += "|-(0)-[v]-(0)-|"
verticalVisualFormat += "|-(0)-[v((width))]"
case UIRectEdge.left:
horizontalVisualFormat += "|-(0)-[v((width))]"
verticalVisualFormat += "|-(0)-[v]-(0)-|"
case UIRectEdge.right:
horizontalVisualFormat += "[v((width))]-(0)-|"
verticalVisualFormat += "|-(0)-[v]-(0)-|"
default:
break
}
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: horizontalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: verticalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
}
}
}
}
}
If I add cornerRadius to v
UIView the result is this:
Any ideas?
Thank you in advance
2
Answers
You can do it with autolayout, take a look to this example:
This is the result:
I would strongly suggest using a custom
UIView
subclass, rather than aUIView
extension. Many advantages.So, simple example…
First, we’ll use Matt’s
CGRect
extension (from this answer) to make things a bit easier:then, a
UIView
subclass that does all the work:and an example view controller showing it "in action":
The output: