.removeFromSuperview不适用于UIImageView

时间:2016-02-26 06:36:16

标签: ios xcode memory uiimageview swift2

我试图以编程方式创建一系列从一个到另一个淡入淡出的背景图像。

我遇到了内存问题,因为在我们的淡出动画完成后,我似乎并没有成功删除我正在创建的UIImageView

在我的后台控制器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()的{​​{1}}函数,它执行相同的操作,但在将createInvisibleBackgroundImage()附加到超级视图之前,将alpha属性设置为0。< / p>

在我的UIImageView文件中

ViewController.swift

我注意到即使我说在bg2淡入完成后从superview中删除了bg1,内存使用量也没有变化(49mb)

如何从内存中删除bg1,以便我可以循环显示更多图像而不会叠加?

1 个答案:

答案 0 :(得分:0)

使用UIImage(named: String)永久缓存图像!

相反,我使用了UIImage(contentsOfFile: String)并删除了对UIImage的所有引用,然后它们起作用了!

请参阅UIImage using contentsOfFile了解详情!