Animation เปลี่ยนสีพื้นหลัง UIView ด้วย UIView.animate
ใช้ UIView.animate(withDuration:animations:) สร้างการเปลี่ยนสีพื้นหลังแบบนุ่มนวล
ขั้นตอนที่ 1: สร้างโปรเจกต์
Xcode → Single View App → ชื่อ "ChangeBGColor"
ขั้นตอนที่ 2: เพิ่ม Button ใน Storyboard
ตั้ง Title ว่า "Change Background Color"
ขั้นตอนที่ 3: สร้าง IBAction
@IBAction func changeBackgroundClicked(_ sender: Any) {
let newColor: UIColor = (view.backgroundColor == .systemRed) ? .systemBlue : .systemRed
UIView.animate(withDuration: 2.0) {
self.view.backgroundColor = newColor
}
}
ขั้นตอนที่ 4: รันทดสอบ
กดปุ่ม → สีพื้นหลังจะเปลี่ยนจากแดง↔น้ำเงิน ภายใน 2 วินาที แบบ Smooth
ขยายความสามารถ: Animation แบบซ้ำ (Repeat)
UIView.animate(withDuration: 2.0, delay: 0, options: [.repeat, .autoreverse], animations: {
self.view.backgroundColor = .systemBlue
}, completion: nil)
Animation แบบ Spring (iOS 7+)
UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: [], animations: {
self.view.backgroundColor = .systemBlue
}, completion: nil)
หมายเหตุ
- Animation บน
backgroundColorทำงานได้โดยตรง (Animatable property) - สำหรับ Layer properties (เช่น borderColor) ต้องใช้
CABasicAnimationแทน - ใช้
completionclosure หากต้องการทำอะไรหลังจบ Animation