Add just a top border to an UIView with Quartzcore/layer?

GilbertOOI's answer in Swift 2:

let topBorder: CALayer = CALayer()
topBorder.frame = CGRectMake(0.0, 0.0, myView.frame.size.width, 3.0)
topBorder.backgroundColor = UIColor.redColor().CGColor
myView.layer.addSublayer(topBorder)

i've find solution for me, here's the tricks :

CGSize mainViewSize = self.view.bounds.size;
CGFloat borderWidth = 1;
UIColor *borderColor = [UIColor colorWithRed:37.0/255 green:38.0/255 blue:39.0/255 alpha:1.0];
UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, mainViewSize.width, borderWidth)];
topView.opaque = YES;
topView.backgroundColor = borderColor;
topView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;        
[self.view addSubview:topView];

Here's a UIView category that lets you add a layer-back or view-backed border on any side of the UIView: UIView+Borders


I just Testing Bellow few line of Code and it works very nice, just test it in to your Project. hope you'll get your solution easily.

Why to create new View and adding it into your existing view..? For this task simply create one CALayer and add it into your existing UIView's Layer do as following:-

#import <QuartzCore/QuartzCore.h>
- (void)viewDidLoad
{
    CALayer *TopBorder = [CALayer layer];
    TopBorder.frame = CGRectMake(0.0f, 0.0f, myview.frame.size.width, 3.0f);
    TopBorder.backgroundColor = [UIColor redColor].CGColor;
    [myview.layer addSublayer:TopBorder];

  [super viewDidLoad];

}

and It's Output is:-

enter image description here

Tags:

Ios

Uiview

Layer