如何从 effectView 中删除 imageView

How to remove imageView from effectView

如何从 effectView 中删除 imageView?目前,当用户失去 Internet 连接时,我正在对其进行动画处理。但是我不知道如何在建立连接后删除 imageVieweffectView 被动画化,但图像仍在视图中。我尝试使用 removeFromSuperview(),但很可能我没有以正确的方式使用它。

func internetConnection() {
    let image = UIImage(named: "nointernet.png")
    let imageView = UIImageView(image: image!)

    if reach.connection == .none {

        imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        imageView.center = self.effectView.center
        self.effectView.contentView.addSubview(imageView)
        effectView.isUserInteractionEnabled = true

        imageView.alpha = 0

        UIView.animate(withDuration: 0.4) {
            self.effectView.effect = self.effect
            imageView.alpha = 1
            imageView.transform = CGAffineTransform.identity
        }
    }else{
        effectView.isUserInteractionEnabled = false
        UIView.animate(withDuration: 0.3, animations: {
            imageView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
            imageView.alpha = 0

            self.effectView.effect = nil

        }) { (Bool) in
            imageView.removeFromSuperview()
        }
    }
}

问题是当连接恢复时,您创建了一个新的图像视图,然后尝试删除新的图像视图。但是您需要删除现有的图像视图。更新您的代码以访问 effectView 中现有的图像视图并将其删除。

func internetConnection() {
    if reach.connection == .none {
        let image = UIImage(named: "nointernet.png")!
        let imageView = UIImageView(image: image)
        imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        imageView.center = self.effectView.center
        imageView.alpha = 0

        self.effectView.contentView.addSubview(imageView)
        effectView.isUserInteractionEnabled = true

        UIView.animate(withDuration: 0.4) {
            self.effectView.effect = self.effect
            imageView.alpha = 1
            imageView.transform = CGAffineTransform.identity
        }
    } else {
        if let imageView = self.effectView.contentView.subviews.last as? UIImageView {
            effectView.isUserInteractionEnabled = false
            UIView.animate(withDuration: 0.3, animations: {
                imageView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
                imageView.alpha = 0

                self.effectView.effect = nil
            }) { (finished) in
                imageView.removeFromSuperview()
            }
        }
    }
}

一个唯一的潜在问题。确保 internetConnection 在连接丢失时不会连续调用两次。否则,您最终会向 effectView 添加多个图像视图。