how do i animate glass items in and out? give me code sample

Asked on 2025-06-26

1 search

To animate glass items in and out in a UIKit app, you can use the UIVisualEffectView with a UIGlassEffect. Here's a code sample to help you get started:

import UIKit

class ViewController: UIViewController {
    
    var glassView: UIVisualEffectView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create a UIVisualEffectView with a glass effect
        let glassEffect = UIBlurEffect(style: .systemMaterial)
        glassView = UIVisualEffectView(effect: glassEffect)
        
        // Set the frame or constraints for the glassView
        glassView.frame = CGRect(x: 50, y: 50, width: 200, height: 200)
        view.addSubview(glassView)
        
        // Add a button to trigger the animation
        let button = UIButton(type: .system)
        button.setTitle("Animate Glass", for: .normal)
        button.addTarget(self, action: #selector(animateGlass), for: .touchUpInside)
        button.frame = CGRect(x: 50, y: 300, width: 200, height: 50)
        view.addSubview(button)
    }
    
    @objc func animateGlass() {
        // Animate the glass effect in and out
        UIView.animate(withDuration: 0.5) {
            if self.glassView.effect == nil {
                self.glassView.effect = UIBlurEffect(style: .systemMaterial)
            } else {
                self.glassView.effect = nil
            }
        }
    }
}

In this example, a UIVisualEffectView is created with a glass effect. The animateGlass function toggles the glass effect on and off with an animation. This approach ensures that the glass effect materializes and dematerializes smoothly.

For more detailed information on animating glass items, you can refer to the session Build a UIKit app with the new design (22:50).