I have this project SwiftySwitch.
My goal is to make the circle expand and detract maintaining the form of a circle instead of having a corner radius that is larger than the current circle height in each specific moment of the animation.
This code handling the circle growing is here:
func turnOn() {
let tempView = UIView(frame: CGRect(x: ballDiameter / 2, y: ballDiameter / 2, width: 0, height: 0))
tempView.backgroundColor = onColor
tempView.layer.cornerRadius = ballDiameter / 2
self.addSubview(tempView)
UIView.animate(withDuration: dotTravelTime, animations: { [weak self] in
//RIGHT HERE is the code for the circle to hold it's circular form
if self != nil {
tempView.frame = CGRect(x: 0, y: 0, width: self!.ballDiameter, height: self!.ballDiameter)
tempView.layer.cornerRadius = self!.ballDiameter / 2
}
self?.layoutIfNeeded()
}) { [weak self] _ in
self?.backgroundColor = self!.onColor
tempView.removeFromSuperview()
}
}
func turnOff() {
let tempView = UIView(frame: CGRect(x: 0, y: 0, width: ballDiameter, height: ballDiameter))
tempView.backgroundColor = onColor
self.addSubview(tempView)
self.backgroundColor = offColor
UIView.animate(withDuration: dotTravelTime, animations: { [weak self] in
//RIGHT HERE is the code for the circle to hold it's circular form
if self != nil {
tempView.frame = CGRect(x: self!.ballDiameter / 2, y: self!.ballDiameter / 2, width: 0, height: 0)
tempView.layer.cornerRadius = self!.ballDiameter / 2
}
self?.layoutIfNeeded()
}) { _ in
tempView.removeFromSuperview()
}
}
Where I say RIGHT HERE is the place where I handle the circle animation. I use a temp UIView to handle the animation and then remove the view after changing the color of the actual view behind it. The tempView is the circle Switch that you see change with the sliding animation. If you need any information about my design let me know. I tried a lot of things, and the all resolved with the circle being a square or having slightly larger corner radius than I desired. (I think it is shrinking the corner radius some from the original size, but it is minor.