我正在尝试以编程方式创建一系列背景图像,这些图像会从一个淡入淡出到另一个。
我的内存有问题,因为我似乎没有成功删除我在淡出动画完成后创建的 UIImageView
。
在我的后台 Controller swift 文件中,我有以下内容:
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
}
我还有一个与 createBackgroundImage()
类似的函数,称为 createInvisibleBackgroundImage()
,它做同样的事情,但给出了 UIImageView
在将其附加到 Superview 之前设置为 0 的 alpha 属性。
在我的 ViewController.swift
文件中有
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)
我注意到即使我已经说过在 bg2 淡入完成后从 superview 中删除 bg1,内存使用量仍未改变 (49mb)
如何从我的内存中删除 bg1,以便我可以循环浏览更多图像而不让它们堆积起来?
最佳答案
原来使用 UIImage(named: String)
永久缓存图像!
相反,我使用了 UIImage(contentsOfFile: String)
并删除了对 UIImage 的所有引用,然后它就起作用了!
参见 UIImage using contentsOfFile了解更多信息!
关于ios - .removeFromSuperview 不适用于 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35645087/