I am trying to programatically create a series of background images that fade from one to another.
I am having trouble with memory as it doesn't seem as though I am successfully removing the UIImageView
that I'm creating after their fade out animation is complete.
In my background controller swift file I have the following:
let URL1 = "bg_1.jpg"
let img1 = UIImage(named: URL1)
let URL2 = "bg_2.jpg"
let img2 = UIImage(named: URL2)
let imagesArray: [UIImage] = [
img1!,
img2!,
]
var backgroundImageArray: [UIImageView] = []
func createBackgroundImage(view: UIView, backgroundImage: UIImage) -> UIImageView {
let backgroundImageView = UIImageView(image: backgroundImage)
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(backgroundImageView)
let horizontalConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
view.addConstraint(verticalConstraint)
let widthConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)
view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)
view.addConstraint(heightConstraint)
backgroundImageView.contentMode = .ScaleAspectFill
return backgroundImageView
}
I also have a similar function to createBackgroundImage()
that is called createInvisibleBackgroundImage()
which does the same thing but instead gives the UIImageView
an alpha property of 0 before attaching it to the Superview.
In my ViewController.swift
file I have
func animateBackgroundImages(iteration: Int, mainView: UIView) {
if iteration == 0 {
var bg1: UIImageView = createBackgroundImage(mainView, backgroundImage: imagesArray[0])
var bg2: UIImageView = createInvisibleBackgroundImage(mainView, backgroundImage: imagesArray[1])
UIView.animateWithDuration(5.0, delay: 1.0, options: UIViewAnimationOptions.TransitionNone, animations: {
bg2.alpha = 1
}, completion: {
(Bool) in
bg1.removeFromSuperview()
})
}
if iteration > 0 && iteration < 7 {
// This is for later when I get it working
}
}
animateBackgroundImages(0, mainView: view)
I am noticing that even though i have said remove bg1 from the superview after the fade in of bg2 is complete the memory usage is unchanged (49mb)
How do I remove bg1 from my memory so that I can in cycle through more images without them stacking up?