How to add a border just on the top side of a UIView

23 Solutions Collect From Internet About “How to add a border just on the top side of a UIView”

I consider subclassing UIView and overriding drawRect overkill here. Why not add a category on UIView and use CALayers

- (void)prefix_addUpperBorder
{
  CALayer *upperBorder = [CALayer layer];
  upperBorder.backgroundColor = [[UIColor greenColor] CGColor];
  upperBorder.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), 1.0f);
  [self.layer addSublayer:upperBorder];
}

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. You could even add a typedef and make the method switch to determine the side to render the border on. Pass in other arguments to your methods to define other colours and widths. Many options.

Worth mentioning to use CALayer will require you to #import <QuartzCore/QuartzCore.h>. I usually do that in some global place like the precompiled header.


Edit 05/05/15

I came to need the functionality I described in my original answer – “You could even add a typedef and make the method switch to determine the side to render the border on”.

Thought I may as well add it to this answer:

- (CALayer *)prefix_addUpperBorder:(UIRectEdge)edge color:(UIColor *)color thickness:(CGFloat)thickness
{
    CALayer *border = [CALayer layer];

    switch (edge) {
        case UIRectEdgeTop:
            border.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), thickness);
            break;
        case UIRectEdgeBottom:
            border.frame = CGRectMake(0, CGRectGetHeight(self.frame) - thickness, CGRectGetWidth(self.frame), thickness);
            break;
        case UIRectEdgeLeft:
            border.frame = CGRectMake(0, 0, thickness, CGRectGetHeight(self.frame));
            break;
        case UIRectEdgeRight:
            border.frame = CGRectMake(CGRectGetWidth(self.frame) - thickness, 0, thickness, CGRectGetHeight(self.frame));
            break;
        default:
            break;
    }

    border.backgroundColor = color.CGColor;

    [self.layer addSublayer:border];

    return border;
}

Edit 19/10/15

People have been asking for an AutoLayout type of solution. Here you go (moved to Swift now too):

Edit 23/3/17
Edited to support Swift 3.0

func addBorder(edges: UIRectEdge, color: UIColor = UIColor.white, thickness: CGFloat = 1.0) -> [UIView] {

    var borders = [UIView]()

    func border() -> UIView {
        let border = UIView(frame: CGRect.zero)
        border.backgroundColor = color
        border.translatesAutoresizingMaskIntoConstraints = false
        return border
    }

    if edges.contains(.top) || edges.contains(.all) {
        let top = border()
        addSubview(top)
        addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[top(==thickness)]",
                options: [],
                metrics: ["thickness": thickness],
                views: ["top": top]))
        addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[top]-(0)-|",
                options: [],
                metrics: nil,
                views: ["top": top]))
        borders.append(top)
    }

    if edges.contains(.left) || edges.contains(.all) {
        let left = border()
        addSubview(left)
        addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[left(==thickness)]",
                options: [],
                metrics: ["thickness": thickness],
                views: ["left": left]))
        addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[left]-(0)-|",
                options: [],
                metrics: nil,
                views: ["left": left]))
        borders.append(left)
    }

    if edges.contains(.right) || edges.contains(.all) {
        let right = border()
        addSubview(right)
        addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "H:[right(==thickness)]-(0)-|",
                options: [],
                metrics: ["thickness": thickness],
                views: ["right": right]))
        addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[right]-(0)-|",
                options: [],
                metrics: nil,
                views: ["right": right]))
        borders.append(right)
    }

    if edges.contains(.bottom) || edges.contains(.all) {
        let bottom = border()
        addSubview(bottom)
        addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "V:[bottom(==thickness)]-(0)-|",
                options: [],
                metrics: ["thickness": thickness],
                views: ["bottom": bottom]))
        addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[bottom]-(0)-|",
                options: [],
                metrics: nil,
                views: ["bottom": bottom]))
        borders.append(bottom)
    }

    return borders
}

// Usage:         
container.addBorder(edges: [.all]) // All with default arguments 
container.addBorder(edges: [.top], color: UIColor.greenColor()) // Just Top, green, default thickness
container.addBorder(edges: [.left, .right, .bottom], color: UIColor.redColor(), thickness: 3) // All except Top, red, thickness 3

Swift version of Adam Waite’s awesome 5/5/15 addition:

extension CALayer {

  func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    var border = CALayer()

    switch edge {
    case UIRectEdge.Top:
        border.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), thickness)
        break
    case UIRectEdge.Bottom:
        border.frame = CGRectMake(0, CGRectGetHeight(self.frame) - thickness, CGRectGetWidth(self.frame), thickness)
        break
    case UIRectEdge.Left:
        border.frame = CGRectMake(0, 0, thickness, CGRectGetHeight(self.frame))
        break
    case UIRectEdge.Right:
        border.frame = CGRectMake(CGRectGetWidth(self.frame) - thickness, 0, thickness, CGRectGetHeight(self.frame))
        break
    default:
        break
    }

    border.backgroundColor = color.CGColor;

    self.addSublayer(border)
  }
}

Swift 3:

extension CALayer {

    func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

        let border = CALayer()

        switch edge {
        case UIRectEdge.top:
            border.frame = CGRect.init(x: 0, y: 0, width: frame.width, height: thickness)
            break
        case UIRectEdge.bottom:
            border.frame = CGRect.init(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
            break
        case UIRectEdge.left:
            border.frame = CGRect.init(x: 0, y: 0, width: thickness, height: frame.height)
            break
        case UIRectEdge.right:
            border.frame = CGRect.init(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
            break
        default:
            break
        }

        border.backgroundColor = color.cgColor;

        self.addSublayer(border)
    }
}

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.

- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
    border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
    [self addSubview:border];
}

- (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
    border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
    [self addSubview:border];
}

- (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin];
    [self addSubview:border];
}

- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin];
    border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
    [self addSubview:border];
}

Subclass UIView and implement drawRect: in your subclass, e.g.:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMinY(rect));
    CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor] );
    CGContextSetLineWidth(context, 2.0);
    CGContextStrokePath(context);
}

This draws a 2 pixel red line as a top border. All of the other variations you mention are left as a trivial exercise for the reader.

Quartz 2D Programming Guide is recommended.

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:

NSInteger borderThickness = 1;

Then just copy use any or all of these to set the border you want to set.

Top Border

UIView *topBorder = [UIView new];
topBorder.backgroundColor = [UIColor lightGrayColor];
topBorder.frame = CGRectMake(0, 0, myView.frame.size.width, borderThickness);
[myView addSubview:topBorder];

Bottom Border

UIView *bottomBorder = [UIView new];
bottomBorder.backgroundColor = [UIColor lightGrayColor];
bottomBorder.frame = CGRectMake(0, myView.frame.size.height - borderThickness, myView.frame.size.width, borderThickness);
[myView addSubview:bottomBorder];

Left Border

UIView *leftBorder = [UIView new];
leftBorder.backgroundColor = [UIColor lightGrayColor];
leftBorder.frame = CGRectMake(0, 0, borderThickness, myView.frame.size.height);
[myView addSubview:leftBorder];

Right Border

UIView *rightBorder = [UIView new];
rightBorder.backgroundColor = [UIColor lightGrayColor];
rightBorder.frame = CGRectMake(myView.frame.size.width - borderThickness, 0, borderThickness, myView.frame.size.height);
[myView addSubview:rightBorder];

swift 3.0

extension CALayer {

    func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

        let border = CALayer();

        switch edge {
        case UIRectEdge.top:
            border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness)
            break
        case UIRectEdge.bottom:
            border.frame = CGRect(x:0, y:self.frame.height - thickness, width:self.frame.width, height:thickness)
            break
        case UIRectEdge.left:
            border.frame = CGRect(x:0, y:0, width: thickness, height: self.frame.height)
            break
        case UIRectEdge.right:
            border.frame = CGRect(x:self.frame.width - thickness, y: 0, width: thickness, height:self.frame.height)
            break
        default:
            break
        }

        border.backgroundColor = color.cgColor;

        self.addSublayer(border)
    }

}

Swift version:

var myView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
myView.backgroundColor = UIColor.yellowColor() 

var border = CALayer()
border.backgroundColor = UIColor.lightGrayColor()
border.frame = CGRect(x: 0, y: 0, width: myView.frame.width, height: 0.5)

myView.layer.addSublayer(border)

Edit: For updated versions check my repo here:
https://github.com/goktugyil/EZSwiftExtensions/blob/master/Sources/UIViewExtensions.swift

Look at the addBorder parts

I took both Adam Waite’s and Pauls answers and combined them. I also added the possibility to pipe the selected edges together, so you need to call only one function like so:

[self.view addBordersToEdge:(UIRectEdgeLeft|UIRectEdgeRight)
                  withColor:[UIColor grayColor]
                   andWidth:1.0];

or so:

[self.view addBordersToEdge:(UIRectEdgeAll)
                  withColor:[UIColor grayColor]
                   andWidth:1.0];

What you need to implement is a category on UIView as suggested in other answers with the following implementation:

- (void)addBordersToEdge:(UIRectEdge)edge withColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    if (edge & UIRectEdgeTop) {
        UIView *border = [UIView new];
        border.backgroundColor = color;
        [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
        border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
        [self addSubview:border];
    }

    if (edge & UIRectEdgeLeft) {
        UIView *border = [UIView new];
        border.backgroundColor = color;
        border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
        [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin];
        [self addSubview:border];
    }

    if (edge & UIRectEdgeBottom) {
        UIView *border = [UIView new];
        border.backgroundColor = color;
        [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
        border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
        [self addSubview:border];
    }

    if (edge & UIRectEdgeRight) {
        UIView *border = [UIView new];
        border.backgroundColor = color;
        [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin];
        border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
        [self addSubview:border];
    }
}

Old question, but the autolayout-solution with runtime border adjustments still missing.

borders(for: [.left, .bottom], width: 2, color: .red)

The following UIView extension will add the border only on the given edges. If you change the edges at runtime, the borders will adjust accordingly.

extension UIView {
    func borders(for edges:[UIRectEdge], width:CGFloat = 1, color: UIColor = .black) {

        if edges.contains(.all) {
            layer.borderWidth = width
            layer.borderColor = color.cgColor
        } else {
            let allSpecificBorders:[UIRectEdge] = [.top, .bottom, .left, .right]

            for edge in allSpecificBorders {
                if let v = viewWithTag(Int(edge.rawValue)) {
                    v.removeFromSuperview()
                }

                if edges.contains(edge) {
                    let v = UIView()
                    v.tag = Int(edge.rawValue)
                    v.backgroundColor = color
                    v.translatesAutoresizingMaskIntoConstraints = false
                    addSubview(v)

                    var horizontalVisualFormat = "H:"
                    var verticalVisualFormat = "V:"

                    switch edge {
                    case UIRectEdge.bottom:
                        horizontalVisualFormat += "|-(0)-[v]-(0)-|"
                        verticalVisualFormat += "[v(\(width))]-(0)-|"
                    case UIRectEdge.top:
                        horizontalVisualFormat += "|-(0)-[v]-(0)-|"
                        verticalVisualFormat += "|-(0)-[v(\(width))]"
                    case UIRectEdge.left:
                        horizontalVisualFormat += "|-(0)-[v(\(width))]"
                        verticalVisualFormat += "|-(0)-[v]-(0)-|"
                    case UIRectEdge.right:
                        horizontalVisualFormat += "[v(\(width))]-(0)-|"
                        verticalVisualFormat += "|-(0)-[v]-(0)-|"
                    default:
                        break
                    }

                    self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: horizontalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
                    self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: verticalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
                }
            }
        }
    }
}

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 your UIView, set the height to be 1 or 2 (for your border height at the top of your UIView). And that should do the trick.

Building off of NSBum’s answer, I took a similar approach and created this simple UIView subclass so that it works in Interface Builder and works with constraints: github link
By using CGContextFillRect instead of CGContextStrokePath, I was able to predictably keep the lines completely solid and within the bounds of the view.

Here’s my blog post about it:
http://natrosoft.com/?p=55

— Basically just drop in a UIView in Interface Builder and change its class type to NAUIViewWithBorders.
— Then in your VC’s viewDidLoad do something like:

/* For a top border only ———————————————- */
self.myBorderView.borderColorTop = [UIColor redColor];
self.myBorderView..borderWidthsAll = 1.0f;

/* For borders with different colors and widths ————————— */
self.myBorderView.borderWidths = UIEdgeInsetsMake(2.0, 4.0, 6.0, 8.0);
self.myBorderView.borderColorTop = [UIColor blueColor];
self.myBorderView.borderColorRight = [UIColor redColor];
self.myBorderView.borderColorBottom = [UIColor greenColor];
self.myBorderView.borderColorLeft = [UIColor darkGrayColor];

Here’s a direct link to the .m file so you can see the implementation.
There is a demo project as well. Hope this helps someone 🙂

My answer to a similar question: https://stackoverflow.com/a/27141956/435766
I personally prefer going down the category road on that one, since I want to be able to use it on any subclass of UIView.

If I’m building from within the storyboard, I prefer add an UIView behind my useful UIView… If I want to create a border on the top of my UIView, I just increase the height of the background UIView by my border width.. The same can be done for any other side 🙂

Just posting here to help someone looking for adding borders. I have made a few changes in the accepted answer here swift label only border left.
Changed width in case UIRectEdge.Top from CGRectGetHeight(self.frame) to CGRectGetWidth(self.frame) and in case UIRectEdge.Bottom from UIScreen.mainScreen().bounds.width to CGRectGetWidth(self.frame) to get borders correctly. Using Swift 2.

Finally the extension is :

extension CALayer {

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer();

    switch edge {
    case UIRectEdge.Top:
        border.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), thickness); 
        break
    case UIRectEdge.Bottom:
        border.frame = CGRectMake(0, CGRectGetHeight(self.frame) - thickness, CGRectGetWidth(self.frame), thickness)
        break
    case UIRectEdge.Left:
        border.frame = CGRectMake(0, 0, thickness, CGRectGetHeight(self.frame))
        break
    case UIRectEdge.Right:
        border.frame = CGRectMake(CGRectGetWidth(self.frame) - thickness, 0, thickness, CGRectGetHeight(self.frame))
        break
    default:
        break
    }

    border.backgroundColor = color.CGColor;

    self.addSublayer(border)
}

}

Personally I like the sub-classing of the view + drawRect, but here’s just another way of going about it (and it kind of works along the same lines as the accepted answer by @If Pollavith):

Your new border layer can be set up to have whatever dimensions you like. So, like @If Pollavith’s answer, you create a layer to be as tall as you want it to be, and as wide as the view you want to have bordered. Use the layer’s frame definition to place it where you want it, and then add it as a sub-layer to your view.

For reference, my own requirement was to put a border on the LEFT-HAND side of the view (please don’t cut and paste this code and dis’ me just ‘cos it doesn’t put a border at the top of the view — modifying the code below is simple enough):

    CALayer *leftBorder = [CALayer layer];
leftBorder.borderColor = [UIColor colorWithRed:0.0 green:91.0/255.0 blue:141.0/255.0 alpha:1.0].CGColor;
leftBorder.borderWidth = 1;
leftBorder.frame = CGRectMake(0, 0, 1.0, CGRectGetHeight(self.myTargetView.frame));
[self.myTargetView.layer addSublayer:leftBorder];

I guess the only moderate benefit over this and making a small UIView or UILabel is that the CALayer is supposedly ‘lighter-weight’, and there’s a lot of interesting views (as in opinions) about over-riding drawRect versus using CALayers (like here: iOS: Using UIView's 'drawRect:' vs. its layer's delagate 'drawLayer:inContext:').

Animal451

I like the colour blue.

In addition to n8tr can add that there is an availability to set them from storyboard either:
– add two properties like borderColor and borderWidth in .h file;
– then you could add keyPaths right in storyboard, see link to screenshot

private class BorderView: UIView {

    var borderWidth = CGFloat(0) {
        didSet {
            setNeedsDisplay()
        }
    }

    var borderColor: UIColor? {
        didSet {
            setNeedsDisplay()
        }
    }

    var edges: UIRectEdge = [] {
        didSet {
            setNeedsDisplay()
        }
    }

    private override func drawRect(var rect: CGRect) {
        super.drawRect(rect)
        if let color = borderColor?.CGColor {
            let context = UIGraphicsGetCurrentContext()
            CGContextSetStrokeColorWithColor(context, color)
            CGContextSetLineWidth(context, borderWidth)
            let correction = borderWidth / 2
            if edges.contains(.All) {
                rect.origin.x += correction
                rect.origin.y += correction
                rect.size.height -= borderWidth
                rect.size.width -= borderWidth
                CGContextAddRect(context, rect)
            } else {
                if edges.contains(.Top) {
                    CGContextMoveToPoint(context, 0, correction)
                    CGContextAddLineToPoint(context, rect.maxX, correction)
                }
                if edges.contains(.Bottom) {
                    CGContextMoveToPoint(context, 0, rect.maxY - correction)
                    CGContextAddLineToPoint(context, rect.maxX, rect.maxY - correction)
                }
                if edges.contains(.Left) {
                    CGContextMoveToPoint(context, correction, 0)
                    CGContextAddLineToPoint(context, correction, rect.maxY)
                }
                if edges.contains(.Right) {
                    CGContextMoveToPoint(context, rect.maxX - correction, 0)
                    CGContextAddLineToPoint(context, rect.maxX - correction, rect.maxY)
                }
            }
            CGContextStrokePath(context)
        }
    }   
}

extension UIView {

    func addBorder(edges: UIRectEdge = .All, color: UIColor = UIColor.whiteColor(), thickness: CGFloat = 1) {
        let borderView = BorderView(frame: bounds)
        borderView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        addSubview(borderView)
        borderView.userInteractionEnabled = false
        borderView.borderColor = color
        borderView.borderWidth = thickness
        borderView.backgroundColor = UIColor.clearColor()
        borderView.edges = edges
    }

}

Convert DanShev answer to Swift 3

extension CALayer {

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer()

    switch edge {
    case .top:
        border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness)
        break
    case .bottom:
        border.frame = CGRect(x: 0, y: self.frame.height - thickness, width: self.frame.width, height: thickness)
        break
    case .left:
        border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.frame.height)
        break
    case .right:
        border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: self.frame.height)
        break
    default:
        break
    }

    border.backgroundColor = color.cgColor;

    self.addSublayer(border)
}
}

For Xamarin in C# I just create the border inline when adding the sub layer

  View.Layer.AddSublayer(new CALayer()
    {
        BackgroundColor = UIColor.Black.CGColor,
        Frame = new CGRect(0, 0, View.Frame.Width, 0.5f)
    });

You can arrange this (as suggested by others) for bottom, left and right borders.

You can also check this collection of UIKit and Foundation categories: https://github.com/leszek-s/LSCategories

It allows adding border on one side of UIView with single line of code:

[self.someView lsAddBorderOnEdge:UIRectEdgeTop color:[UIColor blueColor] width:2];

and it properly handles view rotation while most of answers posted here do not handle it well.

Note: most solutions here are not adaptive and will not resize. The solutions that will resize will have a massive impact on your startup time since they use a lot of CPU.

You can use this solution beneath. It works on UIBezierPaths which are lighter than layers, causing quick startup times. It is easy to use, see instructions beneath.

class ResizeBorderView: UIView {
    var color = UIColor.white
    var lineWidth: CGFloat = 1
    var edges = [UIRectEdge](){
        didSet {
            setNeedsDisplay()
        }
    }
    override func draw(_ rect: CGRect) {
        if edges.contains(.top) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0, y: 0 + lineWidth / 2))
            path.addLine(to: CGPoint(x: self.bounds.width, y: 0 + lineWidth / 2))
            path.stroke()
        }
        if edges.contains(.bottom) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0, y: self.bounds.height - lineWidth / 2))
            path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - lineWidth / 2))
            path.stroke()
        }
        if edges.contains(.left) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0 + lineWidth / 2, y: 0))
            path.addLine(to: CGPoint(x: 0 + lineWidth / 2, y: self.bounds.height))
            path.stroke()
        }
        if edges.contains(.right) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: 0))
            path.addLine(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: self.bounds.height))
            path.stroke()
        }
    }
}
  1. Set your UIView’s class to ResizeBorderView
  2. Set the color and line width by using yourview.color and yourview.lineWidth in your viewDidAppear method
  3. Set the edges, example: yourview.edges = [.right, .left] ([.all]) for all
  4. Enjoy quick start and resizing borders

In case someone will ever need Xamarin version:

public static class UIUtils
{
    public static void AddBorder(this CALayer cALayer, UIRectEdge edge, UIColor color, float thickness)
    {

        var border = new CALayer();
        switch (edge) 
        {
            case UIRectEdge.Top:
                border.Frame = new CGRect(0, 0, cALayer.Frame.Width, height: thickness);
                break;
            case UIRectEdge.Bottom:
                border.Frame = new CGRect(0, cALayer.Frame.Height - thickness, width: cALayer.Frame.Width, height: thickness);
                break;
            case UIRectEdge.Left:
                border.Frame = new CGRect(0, 0, width: thickness, height: cALayer.Frame.Height);
                break;
            case UIRectEdge.Right:
                border.Frame = new CGRect(cALayer.Frame.Width - thickness, y: 0, width: thickness, height: cALayer.Frame.Height);
                break;
            default: break;
        }
        border.BackgroundColor = color.CGColor;
        cALayer.AddSublayer(border);
    }
}

Use below code in viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];


    [self.view.layer setBorderWidth: 1.0];
    [self.view.layer setCornerRadius:8.0f];
    [self.view.layer setMasksToBounds:YES];
    [self.view.layer setBorderColor:[[UIColor colorWithRed:251.0f/255.0f green:185.0f/255.0f blue:23.0f/255.0f alpha:1.0f]];`

}

this code set red color border to your view