Add a border outside of a UIView instead of inside
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
When it comes to designing an iOS app, aesthetics play a significant role in the user experience. A seemingly simple task, such as adding a border to a UIView
, can have a substantial impact on how the interface appears. Developers often need the border to appear outside the view rather than inside it. This distinction is crucial, as a border placed inside can affect the layout and padding of the view's content.
The default behavior when adding a border to a UIView
is for it to appear inside the view's boundaries. This behavior occurs when you set the layer.borderWidth
, layer.borderColor
, and other properties directly on the view's layer. While this may be sufficient in some cases, there are situations where an outer border is more appropriate. This article will discuss how to create an external border around a UIView
.
Technical Explanation
In iOS, UIView
inherits from UIResponder
and is the base class for all views. When customizing the appearance of a view, it's common to manipulate its layer
. The layer
provides properties like borderWidth
, borderColor
, and cornerRadius
, which can adjust the visual aspects of the view.
However, using the layer
to set a border affects the view's internal layout since it expands inward. When you need the border outside the UIView
, you must adopt a different approach.
Method 1: Using a Container View
One straightforward solution to create an external border is to wrap the UIView
inside another UIView
. Here's how you can do it:
- Create a Container View: Add a new
UIViewthat will act as the border. - Add Original View Inside: Place the original
UIViewinside the container. - Adjust Padding: Set the padding/margins such that the original view’s size is reduced by double the border width on all sides.
- Set Border on Container: Apply the border properties to the container
UIView.
Here's a code example:
- Dynamic Border Width and Color: If the border's properties need to change dynamically based on user interaction or other events, encapsulating these in a custom class simplifies the implementation.
- Nested UIViews: For interfaces that have various nested views with distinct styles, segregating the border from the main content is often necessary for layout coherence.

