ios - UICollectionView 不重新加载数据

标签 ios json swift uicollectionview http-post

我有一个 TableView,其中每个项目都有一个代码,当用户选择此表的任何项目时,它必须通过 HTTP-POST 在服务器上获取数据并在另一个 View 中加载 CollectionView。

当这个新 View 打开时,数据集合是空的,然后挤压一个线程通过 HTTP-POST 获取数据,搜索工作正常,但在填充集合后数据没有出现在 CollectionView 中。

这是我的代码:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

@IBOutlet var root: UIView!
@IBOutlet weak var lbDescricao: UILabel!
@IBOutlet weak var colData: UICollectionView!

var desc: String = ""
var codigoCategoria: Int!
var listaProdutos: Array<Produto>!
var items: [IndexPath] = Array()

override func viewDidLoad() {
    super.viewDidLoad()
    self.doPostProdutos()
    lbDescricao.text = self.desc
    print( self.listaProdutos ) // Here it show “nil”
}

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

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    self.items.append(indexPath)
}

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

    cell.imgProduto.image = UIImage( named: listaProdutos[indexPath.item].imagem )
    cell.lbNome.text = listaProdutos[indexPath.item].nome
    cell.lbPreco.text = "R$ " + String( listaProdutos[indexPath.item].preco )

    return cell;
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let padding: CGFloat = 50
    let collectionViewSize = collectionView.frame.size.width - padding

    return CGSize( width: collectionViewSize/2, height: collectionViewSize/2 )
}

func doPostProdutos() {
    let parameter = ["categoria":self.codigoCategoria]

    let url = URL(string: "localhost/adm/api/produtos/produtosCategoria.php")
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

    let httpBody = try? JSONSerialization.data(withJSONObject: parameter, options: [])
    request.httpBody = httpBody


    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print( response )
        }

        if let data = data {
            DispatchQueue.main.async{ // Thread
                do {
                    self.listaProdutos = Array()

                    let json = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]

                    for prod in json {
                        let nome = prod["nome"] as! String
                        let preco = (prod["preco"] as! NSString).doubleValue
                        let img = prod["imagem"] as! String

                        let produto: Produto = Produto(nome: nome, preco: preco, img: img)

                        self.listaProdutos.append(produto)
                    }

                    // Refresh
                    print( self.listaProdutos )
                    self.colData.reloadData()
                    self.colData.reloadItems(at: self.items)
                }
                catch {
                    print(error)
                }
            }
        }
    }.resume()
}
}

我做错了什么?

最佳答案

您需要将 UICollectionView 上的 delegate 和 dataSource 设置为 self

colData.delegate = self
colData.dataSource = self

您可以在 viewDidLoad() 上执行此操作

关于ios - UICollectionView 不重新加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54442101/

相关文章:

json - 从 Ruby 中的 JSON 文件解析并从嵌套哈希中提取数字

objective-c - 如何使用 Objective C 返回 CGPoints 数组

ios - 类 CKPPTSubTest 在两个框架中都实现了。将使用两者之一。哪个是未定义的

ios - NSPredicate - 核心数据 - 将两个属性相互比较

ios - 应用程序传输安全加载即使添加后也出错

ios - UIScrollView圆顶效果

javascript - JS无法解析带有unicode字符的JSON

java - 如何使用JQuery和JSON获取Collection<Item>

ios - 关于 String 和 c strcpy 的快速问题

ios - 如何在 Swift 中将位置添加到推文?