I would like to know if it is possible for some button to cause fading from one background image to another? The following code that I have leads to a sharp change in the current background-image-1 to a new background-image-2 .
func buttonPressed() { if let image = UIImage(named: "background-image-2") { UIView.animateWithDuration(2, delay: 0, options: .CurveEaseInOut, animations: {_ in self.view.backgroundColor = UIColor(patternImage: image) }, completion: nil) }
thanks
EDIT
Despite the fact that the accepted answer really works, I found slight glitches when quickly switching between images. A similar method using UIView.animateWithDuration solves this:
func buttonPressed() { let oldImageView = UIImageView(image: UIImage(named: "background-image-1")) oldImageView.frame = view.frame let newImageView = UIImageView(image: UIImage(named:"background-image-2")) newImageView.frame = view.frame newImageView.alpha = 0 view.insertSubview(newImageView, aboveSubview: backgroundImageView) view.insertSubview(oldImageView, aboveSubview: newImageView) UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseInOut, animations: { oldImageView.alpha = 0 newImageView.alpha = 1 }, completion: { completed in self.backgroundImageView.image = newImage newImageView.removeFromSuperview() oldImageView.removeFromSuperview() }) }
source share