CAShapeLayer
是一个类,因此是一个引用类型。
let someLine = CAShapeLayer()
是对CAShapeLayer
对象的常量引用。您可以简单地将此引用传递给函数并在函数内修改被引用对象的属性。不需要&
运算符 or inout
:
func setupLine(line: CAShapeLayer, startingPath: CGPath) {
line.path = startingPath
line.strokeColor = UIColor.whiteColor().CGColor
line.fillColor = nil
line.lineWidth = 1
}
let someLine = CAShapeLayer()
setupLine(someLine, startingPath: somePath)
一种可能的替代方法是便利初始化程序
extension CAShapeLayer {
convenience init(lineWithPath path: CGPath) {
self.init()
self.path = path
self.strokeColor = UIColor.whiteColor().CGColor
self.fillColor = nil
self.lineWidth = 1
}
}
以便可以将图层创建为
let someLine = CAShapeLayer(lineWithPath: somePath)
您的游乐场的完整示例。请注意,它使用默认参数使其更加通用:
import UIKit
class ShapedView: UIView{
override var layer: CALayer {
let path = UIBezierPath(ovalInRect:CGRect(x:0, y:0, width: self.frame.width, height: self.frame.height)).CGPath
return CAShapeLayer(lineWithPath: path)
}
}
extension CAShapeLayer {
convenience init(lineWithPath path: CGPath, strokeColor:UIColor? = .whiteColor(), fillColor:UIColor? = nil, lineWidth:CGFloat = 1) {
self.init()
self.path = path
if let strokeColor = strokeColor { self.strokeColor = strokeColor.CGColor } else {self.strokeColor = nil}
if let fillColor = fillColor { self.fillColor = fillColor.CGColor } else {self.fillColor = nil}
self.lineWidth = lineWidth
}
}
let view = ShapedView(frame: CGRect(x:0, y:0, width: 100, height: 100))
结果与默认值:
![截屏](https://i.stack.imgur.com/h8aTK.png)