【问题标题】:How to fetch JSON data for UICollectionView with Alamofire, Swift 4如何使用 Alamofire,Swift 4 为 UICollectionView 获取 JSON 数据
【发布时间】:2018-03-24 14:35:03
【问题描述】:

我有一个 UICollectionView,我正在尝试用 来自服务器 的 JSON 数据填充它。为此,我使用 Alamofire 库。在集合视图中,我们有两个主要方法:

First - 返回集合中的单元格数

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

Second - 返回包含内容的单元格

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "chatMessage", for: indexPath) as! ChatMessageCell
    let messageObj = messagesArray![indexPath.item]
    let messageText = messageObj.userText
    cell.messageText.text = messageText
    return cell
}

为了填充我的收藏,我在 viewDidLoad() 方法中调用了我的 getChatMessages() 方法:

override func viewDidLoad() {
    super.viewDidLoad()

    setUpChatLogCollection()
    setupChatLogCollectionConstraints()
    getChatMessages()

}

所以,我遇到了这个问题 - 似乎只有在 Collection 方法完成后才开始使用 Alamofire 获取服务器数据,所以我的集合没有任何数据可以显示。

伙计们,您如何使用 Alamofire 获取您的收藏数据?

我尝试过 viewWillAppear(),但它给了我与 viewDidLoad() 相同的结果。

【问题讨论】:

    标签: ios swift uicollectionview alamofire


    【解决方案1】:

    我假设您的数据获取方法在同一个视图控制器中。因此,一旦 Alamofire 返回数据,将其加载到您的集合中并在集合视图对象上调用 reloadData() 方法。

    参考:reloadData() on UICollectionView

    【讨论】:

      【解决方案2】:

      在 messageArray 中获取值后重新加载集合视图。

      【讨论】:

        猜你喜欢
        • 2018-09-09
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-26
        相关资源
        最近更新 更多