我的问题是关于标题的.

我不知道如何在特定的一侧添加边框,顶部或底部,任何一侧...

推荐答案

我认为这里的子类化UIView和重写drawRect重写.为什么不在UIView上添加一个扩展,并添加边框子视图?

@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继承的任何东西--在您的项目中可重用,以及其他任何东西.将其他参数传递给您的方法以定义其他 colored颜色 和宽度.有很多 Select .

Ios相关问答推荐

使用NavigationStack和.searchable时如何显示大型导航标题?

为什么Reaction-Native-Vision-Camera不能与闪光灯一起使用?

如何在iPhone 15上消除.NET Maui中状态栏和页面之间的差距

RxSwift:如何使用另外两个可观测对象(其中一个依赖于另一个)创建可观测对象?

UITableViewCell编程约束问题

如何在@AppStorage中存储字体?

iOS Swift 应用程序实例的存活时间

比较 `某个协议` 实例时出现编译错误

在 Swift 中 @MainActor 似乎被 withCheckedContinuation 而不是其他异步调用继承是巧合吗?

如何让替换视图淡入旧视图而不是交叉淡入淡出?

SignalR 永远不会在 iOS 上使用 Xamarin Forms 启动

使用 RxDatasources 作为数据源时如何填充自定义页眉/页脚视图

Flutter 错误:CocoaPods not installed or not in valid state.

在 iOS 中获取设备位置(仅限国家/地区)

通过 segue 传递数据

iOS 中的 Crashlytics 不会继续通过 Fabric 应用程序中的构建您的项目

判断可选数组是否为空

UIButton 事件.有什么不同?

如何使用 AFNetworking 设置超时

Info.plist 实用程序错误:无法打开 Info.plist,因为没有这样的文件