I’m trying to get my UIView to rotate about the z-axis in Swift. But for some reason, the rotation axis is not as expected:
rotatedView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
rotatedView.contentMode = .scaleToFill
rotatedView.layer.transform = CATransform3DMakeRotation(rotatedObjectWrapper.object.rotation, 0, 0, 1)
How do I get the UIView to rotate about the z-axis? Thanks.
UPDATE:
I investigated and realised that the rotation is around the z-axis when I use a Stepper element to control the rotation. For context, the delegate function delegate?.didRotateObject
update rotatedObjectWrapper.object.rotation
value.
Slider:
@IBAction func didChangeRotation(_ sender: UISlider) {
delegate?.didRotateObject(to: Double(angleSlider.value))
}
Stepper (which updates by 0.1 radians):
@IBAction func didChangeStepper(_ sender: Any) {
delegate?.didRotateObject(to: Double(stepper.value))
}
I tried using some animation to change the rotation value, and it sort of rotates around the z-axis, while still having the weird rotation behaviour:
UIView.animate(withDuration: 0.5, animations: {
rotatedView.layer.transform = CATransform3DMakeRotation(rotatedObjectWrapper.object.rotation, 0, 0, 1)
})
Outcome:
UPDATE 2:
I’m trying this out:
testView = CustomObjectView(image: UIImage(named: "black"))
guard let testView = testView else { return }
testView.frame = CGRect(x: rotatedObject.position.x, y: rotatedObject.position.y, width: rotatedObject.width, height: rotatedObject.height)
testView.layer.transform = CATransform3DMakeRotation(rotatedObjectWrapper.object.rotation, 0, 0, 1)
rotatedView.layer.transform = CATransform3DMakeRotation(rotatedObjectWrapper.object.rotation, 0, 0, 1)
print(testView.layer.frame)
print(rotatedView.layer.frame)
rotatedView.layer.frame = testView.layer.frame
print(rotatedView.layer.frame)
print(")))))))")
testView
is still rotating correctly, whereas rotatedView
is still rotating weirdly. The only difference between the two is that rotatedView
is obtained from a dictionary as such:
guard let rotatedView = objectsToViews[rotatedObjectWrapper] else { return }
I’m trying a hackish way to set the rotatedView.layer.frame
to be equal to testView.layer.frame
but it’s not working.
2
Answers
This code rotates a view about the z-axis based on the value of a slider, you can run it in a playground:
It’s not clear why your code isn’t working, since the transform is being set the same way, but it must be in some code that isn’t in your question. What are the values you are passing in for rotation? Are there any sublayer transforms?