我在UIView周围创建了一个标准边框,如下所示:
vwGroup.layer.borderColor = UIColor.yellow.cgColor
vwGroup.layer.borderWidth = 2.0;
但是我想在UIView和它周围的边框之间有5px的填充/边距/间距。
现在,它会立即在其周围绘制边框。我想将其推出,以便在它们之间留有清晰的空间。
有什么建议吗?我怀疑插图是可行的方法,但无法弄清楚。
谢谢!
答案 0 :(得分:2)
插入不是要走的路。您可以使用inset从视图的空白处填充视图的内部内容。为此,您最好的选择是将vwGroup
包裹在另一个UIView
中,并在包裹视图中设置边框。像这样:
let wrappingView = UIView(frame: someFrame)
wrappingView.backgroundColor = .clear
wrappingView.layer.borderColor = UIColor.yellow.cgColor
wrappingView.layer.borderWidth = 2.0;
wrappingView.addSubview(vwGroup)
当然,这只是让您了解大局。您可能想要设置适当的框架/约束。
答案 1 :(得分:0)
尝试一下,对您有帮助。
首先,添加此扩展名
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)
}
}
然后添加带有边框的UIView
let vwGroup = UIView(frame: CGRect(x: 50, y: 150, width: 200, height: 200))
vwGroup.backgroundColor = .red
//-- This is for padding between boarder and view -- you can set padding color ---
vwGroup.layer.addGradientBorder(colors:[UIColor.black,UIColor.black] , width: 40)
//-- This is for outer boarder -- you can also change the color of outer boarder --
vwGroup.layer.addGradientBorder(colors:[UIColor.white,UIColor.white] , width: 10)
self.view.addSubview(vwGroup)
输出为:
答案 2 :(得分:0)
swift 5.4
这样调用:
customView.layer.innerBorder()
做到了,通过添加一个子层
extension CALayer {
func innerBorder(borderOffset: CGFloat = 24.0, borderColor: UIColor = UIColor.blue, borderWidth: CGFloat = 2) {
let innerBorder = CALayer()
innerBorder.frame = CGRect(x: borderOffset, y: borderOffset, width: frame.size.width - 2 * borderOffset, height: frame.size.height - 2 * borderOffset)
innerBorder.borderColor = borderColor.cgColor
innerBorder.borderWidth = borderWidth
innerBorder.name = "innerBorder"
insertSublayer(innerBorder, at: 0)
}
}