Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách tạo hiệu ứng chuyển đổi màu nền (background color) cho View trên iOS

Giới thiệu

Bài viết này minh họa cách tạo animation mượt mà khi thay đổi màu nền của view bằng UIView.animate.

Các bước thực hiện

Bước 1: Tạo dự án

Xcode → New Project → Single View Application → Tên "ChangeBGColor".

Bước 2: Thêm Button vào Storyboard

Cách tạo hiệu ứng chuyển đổi màu nền (background color) cho View trên iOS

Bước 3: Tạo IBAction

Kết nối Touch Up Inside của button với hàm changeBackgroundClicked.

Bước 4: Viết code animation

Đổi màu giữa đỏ và xanh lá với animation 2 giây:

@IBAction func changeBackgroundClicked(_ sender: Any) {
    if self.view.backgroundColor == UIColor.red {
        UIView.animate(withDuration: 2.0) {
            self.view.backgroundColor = UIColor.blue
        }
    } else {
        UIView.animate(withDuration: 2.0) {
            self.view.backgroundColor = UIColor.red
        }
    }
}

Bước 5: Chạy thử

Mỗi lần bấm button, màu nền chuyển đổi mượt mà giữa đỏ và xanh:

Cách tạo hiệu ứng chuyển đổi màu nền (background color) cho View trên iOS

Nâng cao: Animation với completion handler

UIView.animate(withDuration: 1.5, animations: {
    self.view.backgroundColor = UIColor.systemPurple
}, completion: { finished in
    print("Animation hoàn tất")
    // Có thể trigger animation tiếp theo ở đây
})

Nâng cao: Spring Animation (iOS 7+)

UIView.animate(withDuration: 1.0,
               delay: 0,
               usingSpringWithDamping: 0.6,
               initialSpringVelocity: 0.8,
               options: .curveEaseInOut,
               animations: {
    self.view.backgroundColor = UIColor.systemOrange
}, completion: nil)

Lưu ý

  • Animation chỉ hoạt động trên main thread (UIKit yêu cầu).
  • withDuration tính bằng giây (Double).
  • Có thể animate nhiều thuộc tính cùng lúc: alpha, transform, frame, bounds, v.v.
  • Để animate gradient, cần dùng CAGradientLayer + CABasicAnimation.