My question is on the title.
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...
My question is on the title.
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...
I consider subclassing
UIView
and overridingdrawRect
overkill here. Why not add an extension onUIView
and add border subviews?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.For me works
Swift version of Adam Waite's awesome 5/5/15 addition:
Swift 3:
The best way for me is a category on UIView, but adding views instead of CALayers, so we can take advantage of AutoresizingMasks to make sure borders resize along with the superview.
Code for the selected answer, in case anyone wants it.
NOTE: This does not work with autolayout (aka, rotating device to landscape, etc).
First define a thickness:
Then just copy use any or all of these to set the border you want to set.
Top Border
Bottom Border
Left Border
Right Border
Here's a simple solution. Add a label onto your
UIView
, clear the text on the label and set the label background color to be your border color. Set the origin(x,y)
of your label to be the origin(x,y)
of your view. and set the width of the label to be the width of yourUIView
, set the height to be 1 or 2 (for your border height at the top of yourUIView
). And that should do the trick.