如何在 UIView 的顶部添加边框 [英] How to add a border just on the top side of a UIView
问题描述
我的问题是关于标题.
我不知道如何在特定的一侧、顶部或底部、任何一侧添加边框...layer.border
为整个视图绘制边框...
I don't know how to add a border in a specific side, top or bottom, any side...
layer.border
draws the border for the whole view...
推荐答案
我认为子类化 UIView
和覆盖 drawRect
在这里是过度的.为什么不在 UIView
上添加扩展并添加边框子视图?
I consider subclassing UIView
and overriding drawRect
overkill here. Why not add an extension on UIView
and add border subviews?
@discardableResult
func addBorders(edges: UIRectEdge,
color: UIColor,
inset: CGFloat = 0.0,
thickness: CGFloat = 1.0) -> [UIView] {
var borders = [UIView]()
@discardableResult
func addBorder(formats: String...) -> UIView {
let border = UIView(frame: .zero)
border.backgroundColor = color
border.translatesAutoresizingMaskIntoConstraints = false
addSubview(border)
addConstraints(formats.flatMap {
NSLayoutConstraint.constraints(withVisualFormat: $0,
options: [],
metrics: ["inset": inset, "thickness": thickness],
views: ["border": border]) })
borders.append(border)
return border
}
if edges.contains(.top) || edges.contains(.all) {
addBorder(formats: "V:|-0-[border(==thickness)]", "H:|-inset-[border]-inset-|")
}
if edges.contains(.bottom) || edges.contains(.all) {
addBorder(formats: "V:[border(==thickness)]-0-|", "H:|-inset-[border]-inset-|")
}
if edges.contains(.left) || edges.contains(.all) {
addBorder(formats: "V:|-inset-[border]-inset-|", "H:|-0-[border(==thickness)]")
}
if edges.contains(.right) || edges.contains(.all) {
addBorder(formats: "V:|-inset-[border]-inset-|", "H:[border(==thickness)]-0-|")
}
return borders
}
// Usage:
view.addBorder(edges: [.all]) // All with default arguments
view.addBorder(edges: [.top], color: .green) // Just Top, green, default thickness
view.addBorder(edges: [.left, .right, .bottom], color: .red, thickness: 3) // All except Top, red, thickness 3
使用此代码,您也不会绑定到您的子类,您可以将其应用到任何继承自 UIView
的所有内容 - 可在您的项目和任何其他项目中重用.将其他参数传递给您的方法以定义其他颜色和宽度.多种选择.
With this code you're not tied to your subclass too, you can apply it to anything and everything that inherits from UIView
- reusable in your project, and any others. Pass in other arguments to your methods to define other colours and widths. Many options.
这篇关于如何在 UIView 的顶部添加边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!