How to do rotation for CALayer in iOS

Issue #229

Use keypath

1
2
3
4
5
6
let animation = CASpringAnimation(keyPath: #keyPath(CALayer.transform))
animation.fromValue = 0
animation.valueFunction = CAValueFunction(name: CAValueFunctionName.rotateZ)
animation.timingFunction = CAMediaTimingFunction(name: .easeIn)

animation.toValue = CGFloat.pi / 4

Avoid setting frame many times

Otherwise, frame is the box that covers the rotation transform, and backgroundColor now fills that huge box

abc

1
2
3
4
5
6
7
8
9
10
11
12
override func layoutSubviews() {
super.layoutSubviews()

guard line.frame.width <= 0 else {
return
}

line.backgroundColor = UIColor.red.cgColor
line.cornerRadius = 3
line.frame.size = CGSize(width: bounds.width*0.6, height: 6)
line.position = layer.position
}

Auto Layout

Avoid using Auto Layout for the rotated view

Comments