无法更改swift类循环Loader的属性

时间:2016-08-22 22:52:24

标签: ios swift class properties uicolor

我使用本教程在Swift中创建了一个类来设置圆形加载动画 https://www.raywenderlich.com/94302/implement-circular-image-loader-animation-cashapelayer,一切正常,但是当我尝试在我想要使用类的视图控制器中更改笔划的颜色时

class CircularLoaderView: UIView {
let circlePathLayer = CAShapeLayer()
var circleRadius: CGFloat = 20.0
var strokeColor = UIColor.whiteColor()


override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    configure()
}

func configure() {
    progress = 0
    circlePathLayer.frame = bounds
    circlePathLayer.lineWidth = 10
    circlePathLayer.fillColor = UIColor.clearColor().CGColor
    circlePathLayer.strokeColor = strokeColor.CGColor
    layer.addSublayer(circlePathLayer)
    backgroundColor = UIColor.clearColor()
}

然后我设置了属性

//LoadingRing
    progressIndicatorView.removeFromSuperview()
    progressIndicatorView.frame = actionView.bounds
    progressIndicatorView.circleRadius = (recordButtonWhiteRing.frame.size.height - 10) / 2
    progressIndicatorView.progress = 0.0
    progressIndicatorView.strokeColor = UIColor.init(red: 232 / 255.0, green: 28 / 255.0, blue: 45 / 255.0, alpha: 1)

但是中风仍然显示为白色而不是所需的颜色,请任何帮助!

1 个答案:

答案 0 :(得分:0)

笔画的颜色由circlePathLayer.strokeColor的值确定,当您创建进度指示器的实例时,您在configure()中修改该值 - 并且在您的实例创建时,strokeColor }是UIColor.whiteColor()

您应该附加一个监听器,以便将您的视图strokeColor与其基础circlePathLayer的视图同步:

var strokeColor = UIColor.whiteColor() {
  didSet {
    circlePathLayer.strokeColor = strokeColor.CGColor
  }
}

或者只是使用getter / setter直接公开重要的strokeColor

var strokeColor: UIColor {
  get {
    guard let cgColor = circlePathLayer.strokeColor else {
      return UIColor.whiteColor()
    }
    return UIColor(CGColor: cgColor)
  }
  set (strokeColor) {
    circlePathLayer.strokeColor = strokeColor.CGColor
  }
}

(编辑:正如Rob指出的那样,CGColor强制转换是必要的,以使这个正确无误。)