Setting multiple borders on UIView

岁酱吖の 提交于 2019-12-01 22:17:00

Three solutions I can think of:

  • nest a UIView in another one, define one border for each;
  • draw the border yourself in -(void)drawRect;
  • use an UIImageView with a resizable; stretchable image of your borders as background (the best solution performance-wise).

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.

This is not possible, you will have to fake borders by adding UIView's with a background color to your xib/view.

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;

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!