ios - 如何在 UIView 的顶部添加边框

我的问题在标题上。

我不知道如何在特定的一侧、顶部或底部、任何一侧添加边框... layer.border 为整个 View 绘制边框...

最佳答案

我在这里考虑继承 UIView 并覆盖 drawRect 过大。为什么不在 UIView 上添加扩展并添加边框 subview ?

@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

使用此代码,您也不会与子类绑定(bind),您可以将其应用于从 UIView 继承的任何事物和所有事物 - 可在您的项目和任何其他项目中重复使用。将其他参数传递给您的方法以定义其他颜色和宽度。很多选择。

https://stackoverflow.com/questions/17355280/

相关文章:

ios - UITableView 设置为静态单元格。是否可以以编程方式隐藏某些单元格?

objective-c - 为什么在 iOS 中使用前导下划线重命名合成属性?

ios - Objective-C中的方法重载?

objective-c - NSInteger 的 NSLog/printf 说明符?

objective-c - 错误 : writable atomic property cannot

ios - SDK iOS 8.0 中的产品类型单元测试包需要代码签名

ios - 如何比较 UIColors?

iphone - 如何自动调整 UIScrollView 的大小以适合其内容

objective-c - 检测 NSString 是否包含...?

ios - 在 iPhone App 中如何检测设备的屏幕分辨率