【问题标题】:UICollectionView not reloading dataUICollectionView 不重新加载数据
【发布时间】:2019-01-30 13:49:40
【问题描述】:

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

当这个新视图打开时,数据集合是空的,然后挤压一个线程以通过 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()
}
}

我做错了什么?

【问题讨论】:

    标签: ios json swift uicollectionview http-post


    【解决方案1】:

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

    colData.delegate = self
    colData.dataSource = self
    

    您可以在 viewDidLoad() 上这样做

    【讨论】:

    • 您应该只设置一次,在刷新中设置它不是一个好习惯。从技术上讲,它会起作用,但如果你把这些属性放在那里,它会变得非常混乱。
    • 我明白了!真的你是对的!这是一种不好的做法!
    【解决方案2】:

    您需要在此处添加这 2 行

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

    添加上面的2行,这样你的collectionView就可以在你reloadData()时获取数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多