-1

How to add a border with specific color and thickness to a UIView when using auto layout in objective-c ?

Fadi Obaji
  • 1,454
  • 4
  • 27
  • 57
  • 2
    For the people downvoting my question and answer, can you please explain why ? this is a very useful function! – Fadi Obaji Apr 21 '16 at 23:06

1 Answers1

2

This function will add a border with specific color and thickness to any border of a UIView

- (void)addBorder:(UIView *)view toEdge:(UIRectEdge)edge withColor:(UIColor *)color withThickness:(float)thickness{
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
    switch (edge) {
        case UIRectEdgeTop:
            border.frame = CGRectMake(0, 0, view.frame.size.width, thickness);
            break;
        case UIRectEdgeBottom:
            border.frame = CGRectMake(0, view.frame.size.height - thickness, view.frame.size.width, thickness);
            break;
        case UIRectEdgeLeft:
            border.frame = CGRectMake(0, 0, thickness, view.frame.size.height);
            break;
        case UIRectEdgeRight:
            border.frame = CGRectMake(view.frame.size.width - thickness, 0, thickness, view.frame.size.height);
            break;
        default:
            break;
    }
    [view addSubview:border];
}

Usage

[self addBorder:yourView toEdge:UIRectEdgeTop withColor:[UIColor greenColor] withThickness:3.0f];

Hope you make use of it all.

Fadi Obaji
  • 1,454
  • 4
  • 27
  • 57