在ScrollView(Swift)中隐藏未使用的图像

时间:2017-08-10 06:29:56

标签: ios swift firebase io scrollview

我需要隐藏未使用的图像。怎么做? 在我的代码中,我有三个图像,但并不总是使用所有图像。如何隐藏第三张图片?后来如果我添加第三个图像,我需要再次取消隐藏此图像而不更改代码。

import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage

class ScrollViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollView: UIScrollView!

var image = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    loadImages()

}
func loadImages() {

    Database.database().reference().child("Студии2").observeSingleEvent(of: .value, with: { (snapshot) in

        let newImages = [String]()

        for child in snapshot.children {
            let snap = child as! DataSnapshot
            let imageSnap = snap.childSnapshot(forPath: "Photo")
            let dict = imageSnap.value as! [String: AnyObject]
            let url = dict["image"] as? String ?? ""
            let url2 = dict["image1"] as? String ?? ""
            let url3 = dict["image3"] as? String ?? ""
            self.image.append(url)
            self.image.append(url2)
            self.image.append(url3)

            for i in 0..<self.image.count {
                let imagesArray = UIImageView()
                imagesArray.sd_setImage(with: URL(string: self.image[i]))
                let xPos = self.view.frame.width * CGFloat(i)
                imagesArray.frame = CGRect(x: xPos, y: 0, width: self.scrollView.frame.width, height: self.scrollView.frame.height)


                self.scrollView.contentSize.width = self.scrollView.frame.width * CGFloat(i + 1)
                self.scrollView.addSubview(imagesArray)
            }
        }
        self.image = newImages
    })
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以过滤掉空白对象,以便内容大小正确

这是怎么做的

func loadImages() {
   Database.database().reference().child("Студии2").observeSingleEvent(of: .value, with: { snapshot in

      for child in snapshot.children {
         guard let snap = child as? DataSnapshot else { return }
         let imageSnap = snap.childSnapshot(forPath: "Photo")
         guard let dict = imageSnap.value as? [String: AnyObject] else { return }

         self.image.append(dict["image"] as? String ?? "")
         self.image.append(dict["image1"] as? String ?? "")
         self.image.append(dict["image3"] as? String ?? "")

         let links = self.image.filter { !$0.isEmpty }

         let size = self.view.frame.size

         links.enumerated().forEach {
            let imageView = UIImageView()
            imageView.sd_setImage(with: URL(string: $0.element))
            let x = size.width * CGFloat($0.offset)
            imageView.frame = CGRect(x: x, y: 0, width: size.width, height: size.height)

            self.scrollView.addSubview(imageView)
         }

         self.scrollView.contentSize.width = size.width * CGFloat(links.count)
      }
      self.image = [String]()
   })
}