Setting multiple borders on UIView

后端 未结 5 453
庸人自扰
庸人自扰 2021-01-13 17:39

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

相关标签:
5条回答
  • 2021-01-13 18:20

    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.

    0 讨论(0)
  • 2021-01-13 18:24

    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;
    
    0 讨论(0)
  • 2021-01-13 18:31

    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).
    0 讨论(0)
  • 2021-01-13 18:34

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

    0 讨论(0)
  • 2021-01-13 18:35

    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:

    0 讨论(0)
提交回复
热议问题