我想在集合视图单元格中使用一些自定义结构。我从API服务获取数据,然后尝试将其传递到我的自定义集合视图单元格。

我找到了几个答案,但我仍然不知道该怎么做

这是我获取实际数据的地方:

    func FetchFormData(linkUrl: String) {

    let parameters: [String: AnyObject] = [:]

    let postString = (parameters.flatMap({ (key, value) -> String in
        return "\(key)=\(value)"
    }) as Array).joined(separator: "&")


    let url = URL(string: linkUrl)!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)

        let contentData = responseString?.data(using: .utf8)
        do {
            let decoder = JSONDecoder()
            self.formData = try decoder.decode(FormModel.self, from: contentData!)

        } catch let err {
            print("Err", err)
        }

        DispatchQueue.main.async {
            //here is the where I reload Collection View
            self.collectionView.reloadData()
        }

    }
    task.resume()
}


同样在这里,我试图将数据传递到单元格:

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

    cell.backgroundColor = .green

    //Data could be print out here
    print(self.formData?.components?[indexPath.row])
    cell.formComponent = (self.formData?.components?[indexPath.row])!

    return cell
}


实际的问题开始进入我的细胞班

class BaseFormCollectionViewCell: UICollectionViewCell {

var formComponent: FormComponent!{
    didSet {
        //data can be print out here
        print("Passed value is: \(formComponent)")
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)

    //this part is always nill
    print(formComponent)

}


}

大家可以在代码中看到直到我的收藏夹视图单元运行良好。
它应该简单得多,但是我不知道发生了什么以及为什么发生。

最佳答案

修改您的单元格类为

class BaseFormCollectionViewCell: UICollectionViewCell {

var formComponent: FormComponent!{
    didSet {
        //this is unnecessary. You can achieve what u want with a bit more cleaner way using configure function as shown below
        //data can be print out here
        print("Passed value is: \(formComponent)")
    }
 }

 override init(frame: CGRect) {
    super.init(frame: frame)

    //this part is always nill
    print(formComponent)

 }

 func configure() {
    //configure your UI of cell using self.formComponent here
 }
}


最后

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

    cell.backgroundColor = .green

    //Data could be print out here
    print(self.formData?.components?[indexPath.row])
    cell.formComponent = (self.formData?.components?[indexPath.row])!
    (cell as! BaseFormCollectionViewCell).configure()
    return cell
}


(cell as! BaseFormCollectionViewCell).configure()中查找cellForItemAt,这就是在将数据传递到上面的语句中的单元格之后,您如何触发单元格的UI配置。

坦率地说,您可以摆脱didSet并在configure上中继,如下所示

希望能帮助到你

08-18 13:04
查看更多