import UIKit
class ColorToggleViewController: UIViewController {
private let squareView = UIView()
private var isToggled = false
private var widthConstraint: NSLayoutConstraint!
private var heightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
squareView.backgroundColor = .systemBlue
squareView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(squareView)
widthConstraint = squareView.widthAnchor.constraint(equalToConstant: 100)
heightConstraint = squareView.heightAnchor.constraint(equalToConstant: 100)
NSLayoutConstraint.activate([
squareView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
squareView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
widthConstraint,
heightConstraint
])
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(squareTapped))
squareView.addGestureRecognizer(tapGesture)
squareView.isUserInteractionEnabled = true
}
@objc private func squareTapped() {
isToggled.toggle()
widthConstraint.constant = isToggled ? 150 : 100
heightConstraint.constant = isToggled ? 150 : 100
UIView.animate(withDuration: 0.5) {
self.squareView.backgroundColor = self.isToggled ? .systemGreen : .systemBlue
self.view.layoutIfNeeded()
}
}
}
We keep references to the width and height constraints so we can change their constants when toggling.
When the square is tapped, we toggle the isToggled boolean.
We update the constraint constants to 150 or 100 depending on the toggle state.
Inside UIView.animate, we change the background color and call layoutIfNeeded() to animate the size change smoothly.
This keeps the square centered and animates both color and size changes over 0.5 seconds.