在viewController的视图中添加一些虚线时,请添加子层。
代码如下:
class ViewController: UIViewController {
@IBOutlet weak var tmpLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tmpLabel.layer.borderColor = UIColor.red.cgColor;
tmpLabel.layer.borderWidth = 2
tmpLabel.addDashedBorders(padding: 50, y: tmpLabel.bounds.size.height * 0.5)
// ......
}}
extension UIView {
func addDashedBorders( padding x: CGFloat, y : CGFloat) {
//Create a CAShapeLayer
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 2
shapeLayer.lineDashPattern = [2,3]
let path = CGMutablePath()
path.addLines(between: [CGPoint(x: x, y: y),
CGPoint(x: bounds.size.width * 0.5 - 50, y: y)])
path.addLines(between: [CGPoint(x: bounds.size.width * 0.5 + 50, y: y),
CGPoint(x: bounds.size.width - x, y: y)])
shapeLayer.path = path
layer.addSublayer(shapeLayer)
}
}
以下图片在iPhoneX中
代码是硬编码的,不好。
我想将子形状图层添加到标签正下方的视图中。
有代码
class ViewController: UIViewController {
@IBOutlet weak var tmpLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tmpLabel.layer.borderColor = UIColor.red.cgColor;
tmpLabel.layer.borderWidth = 2
view.addDashedBorder(padding: 50, y: tmpLabel.frame.origin.y)
//...
}}
extension UIView {
func addDashedBorder( padding x: CGFloat, y : CGFloat) {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 2
shapeLayer.lineDashPattern = [2,3]
let path = CGMutablePath()
path.addLines(between: [CGPoint(x: x, y: y),
CGPoint(x: bounds.size.width - x, y: y)])
shapeLayer.path = path
layer.addSublayer(shapeLayer)
}
}
我在iPhoneX中测试过,有一段距离。
我尝试过view.safeAreaInsets
,全为零。
我想念什么?