How to add a border just on the top side of a UIView
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
UIView does not have a built-in property for per-side borders. If you want a border only on the top edge, the usual solution is to add a thin subview or CALayer positioned at the top of the view.
Why the Default Border Is Not Enough
UIView.layer.borderWidth and UIView.layer.borderColor apply to all four sides equally. That works for a full rectangle border, but not when the design needs only a top separator.
To draw just one side, you create your own drawable element and place it where the border should appear.
A Simple CALayer Approach
CALayer is lightweight and fits this use case well:
The important detail is placing the frame update in viewDidLayoutSubviews(). That ensures the border matches the view's final size after Auto Layout finishes.
Using a Subview Instead
Some teams prefer a thin UIView because it is easier to inspect in the view hierarchy:
This approach is especially convenient when the border must participate in Auto Layout or be animated like a normal view.
Which Approach Should You Use
Use CALayer when:
- the border is purely decorative
- you want minimal overhead
- you do not need layout constraints for the border itself
Use a subview when:
- you want constraint-based layout
- the border may be shown, hidden, or animated as a regular view
- your team prefers UI code that is easier to inspect visually
Both are valid. The key is to avoid using the full view border when only one edge should be drawn.
Reusable Extension Pattern
If you need this often, wrap it in a helper:
For dynamic layouts, call the helper after the view has a valid size, or update the border frame during layout.
If the view is reused inside table or collection cells, it is also worth removing any old border layers before adding a new one. Otherwise repeated configuration can stack multiple top borders on the same view and make the line appear thicker than intended.
Common Pitfalls
- Setting
layer.borderWidthand expecting only the top side to appear. - Adding the border before the view has its final bounds, which leads to the wrong width.
- Adding a new border layer repeatedly during layout and creating duplicates.
- Forgetting to update the border when the view resizes.
- Using a one-pixel assumption without considering screen scale if a very precise visual result is needed.
Summary
- '
UIViewhas no built-in one-sided border API.' - The usual fix is a thin
CALayeror a thin subview pinned to the top edge. - '
CALayeris lightweight and good for decorative borders.' - For Auto Layout-heavy code, a subview can be easier to manage.
- Always size the top border after layout so it matches the final view width.

