Swift初始化类并使用参数和方法



我是swift的新手,我的问题对你们大多数人来说可能是个傻瓜。但不管怎样,我都在努力在实践中学习。这是我的问题。我有一个型号:

import Foundation
import Firebase
struct special {
let name: String
let position: Int
let imageURL: String?
}

class SpecialList {

var specialList: [special] = []
init() {        

}

func loadSpecial () {
db.collection("special").getDocuments { (querySnapshot, error) in
if let e = error {
print("Error(e)")
} else {
if let snapshotDocuments = querySnapshot?.documents {
for doc in snapshotDocuments {
let data = doc.data()
if let name = data["name"] as? String, let position = data["position"] as? Int, let imageURL = data["imageURL"] as? String {
let newList = special(name: name, position: position, imageURL: imageURL)
self.specialList.append(newList)
}
}
}
}
}
}    
}

我正试图在ViewController:中实现这一点

var specialList = SpecialList()
override func viewDidLoad() {
specialList.loadSpecial()
print(specialList.specialList)
}

实际上,我需要的是从firebase中检索到的数据。我试图将它保存在var specialList: [special] = []中,但它总是空的。我想我应该在init((中做点什么,但没有找到正确的方法。

消防基地的p.S.装载工作良好。已检查打印数据。

并且数据应该在集合中查看

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return specialList.specialList.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SpecialCell", for: indexPath as IndexPath) as! SpecialCollectionViewCell

if let imageURL = specialList.specialList[indexPath.row].imageURL {
let url = URL(string: imageURL)
cell.specialPic.kf.setImage(with: url) // download foto
}
cell.specialName.text = specialList.specialList[indexPath.row].name
return cell
}
func loadSpecial (completion: @escaping (Bool) -> Void) {
db.collection("special").getDocuments { (querySnapshot, error) in
if let e = error {
print("Error(e)")
completion(false)
} else {
if let snapshotDocuments = querySnapshot?.documents {
for doc in snapshotDocuments {
let data = doc.data()
if let name = data["name"] as? String, let position = data["position"] as? Int, let imageURL = data["imageURL"] as? String {
let newList = special(name: name, position: position, imageURL: imageURL)
self.specialList.append(newList)
}
}
completion(true)
}
completion(false)
}
}
}

将完成添加到您的方法

在VC中做:

override func viewDidLoad() {
super.viewDidLoad()
specialList.loadSpecial(completion: { [weak self] success in
self.collectionView.reloadData()
})
}

如果收集实现是正确的,你会看到它

在append语句和print语句中设置一个断点,看看先调用哪一个。在获取数据之前,可能会调用print语句。

如果有人有同样的问题。最好的解决方法是使用委托。我添加了额外的:

protocol SpecialListUpdateDelegate {
func didUpdate(sender: SpecialList)
}

在我的班级特殊列表:

var delegate: SpecialListUpdateDelegate?

在loadspecial((中:

self.delegate?.didUpdate(sender: self)

在VC中为VC添加协议:SpecialListUpdateDelegate

在视图中DidLoad:

specialList.delegate = self

最后一个实现功能:

func didUpdate(sender: SpecialList) {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}

最新更新