问题
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 currently setting a standard border with .layer.borderWidth
and layer.borderColor
. I am wondering if I can add a multiple strokes/borders effect to the view.
I need a border of 4.0f in white then another 1.0f in another color.
回答1:
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).
回答2:
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.
回答3:
This is not possible, you will have to fake borders by adding UIView
's with a background color to your xib/view.
回答4:
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;
回答5:
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:
来源:https://stackoverflow.com/questions/18830792/setting-multiple-borders-on-uiview