As I cannot find any questions/answers for this, I imagine it is not possible.
Is there anyway to set multiple borders on a UIView
.
I am curren
That isn't possible with a single UIView
instance without adding layers.
What you can do is create a view that is larger than necessary, set its border appropriately, then add a CALayer
and position it where you want the inner border and set its border properties appropriately.
Using CALayers
is typically faster than full blown UIView
, but you can also just have a nested UIView
to achieve the same effect.
Try this,
I'm adding shadow with alpha 1 which will act as the inner border. And the normal border is given as outer border.
yourView.frame = CGRectInset(yourView.frame, -borderWidth, -borderWidth);
yourView.layer.borderColor = [UIColor blackColor].CGColor;
yourView.layer.borderWidth = borderWidth;
yourView.layer.shadowColor = [UIColor whiteColor].CGColor;
yourView.layer.shadowOffset = CGSizeMake(0, 1);
yourView.layer.shadowOpacity = 1;
yourView.layer.shadowRadius = 1.0;
yourView.clipsToBounds = YES;
Three solutions I can think of:
-(void)drawRect
;UIImageView
with a resizable; stretchable image of your borders as background (the best solution performance-wise).This is not possible, you will have to fake borders by adding UIView
's with a background color to your xib/view.
You can insert two layers of different widths using this extension:
extension CALayer {
func addGradientBorder(colors:[UIColor],width:CGFloat = 1) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(origin: CGPoint.zero, size: self.bounds.size)
gradientLayer.startPoint = CGPoint(x:0.0, y:0.0)
gradientLayer.endPoint = CGPoint(x:1.0,y:1.0)
gradientLayer.colors = colors.map({$0.cgColor})
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = width
shapeLayer.path = UIBezierPath(rect: self.bounds).cgPath
shapeLayer.fillColor = nil
shapeLayer.strokeColor = UIColor.red.cgColor
gradientLayer.mask = shapeLayer
self.addSublayer(gradientLayer)
}
}
Use this with different widths/colors to get the desired effect:
yourView.layer.addGradientBorder(colors:[UIColor.black,UIColor.black] , width: 20)
yourView.layer.addGradientBorder(colors:[UIColor.white,UIColor.white] , width: 10)
Output looks like the following image with outer white border and inner black border: