1
我要顯示這樣一行:畫一條線與CAShapeLayer
這裏是我的代碼:
import UIKit
@IBDesignable
class ProgressView: UIView {
let π = CGFloat(M_PI)
var levelProgress: CGFloat = 0.0 {
didSet {
self.fgLayer.strokeEnd = levelProgress
}
}
let bgLayer = CAShapeLayer()
let fgLayer = CAShapeLayer()
@IBInspectable var bgColor: UIColor = UIColor.black.withAlphaComponent(0.3) {
didSet {
configure()
}
}
@IBInspectable var fgColor: UIColor = UIColor.white {
didSet {
configure()
}
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
configure()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
configure()
}
func setup() {
bgLayer.lineWidth = 4.0
bgLayer.fillColor = nil
bgLayer.strokeEnd = 1
layer.addSublayer(bgLayer)
fgLayer.lineWidth = 4.0
fgLayer.fillColor = nil
fgLayer.strokeEnd = 0.0
layer.addSublayer(fgLayer)
}
func configure() {
bgLayer.strokeColor = bgColor.cgColor
fgLayer.strokeColor = fgColor.cgColor
}
override func layoutSubviews() {
super.layoutSubviews()
setupShapeLayer(shapeLayer: bgLayer)
setupShapeLayer(shapeLayer: fgLayer)
}
private func setupShapeLayer(shapeLayer: CAShapeLayer) {
shapeLayer.frame = self.bounds
let linePath = UIBezierPath()
linePath.move(to: self.frame.origin)
linePath.addLine(to: CGPoint(x: self.frame.origin.x + self.frame.width, y: self.frame.origin.y))
shapeLayer.path = linePath.cgPath
}
}
但運行後,它不會顯示任何東西。
你們都設置代碼來創建行,但你有沒有添加爲uiview的子視圖層? –
不,我已經添加了它。 – Khuong