将数据传递给collectionViewCell

时间:2018-03-21 09:23:32

标签: ios swift uicollectionviewcell

我想在我的集合视图单元格中使用一些自定义结构。我从我的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)

}

}

正如你们在代码中看到的那样,直到我的集合查看单元格才能顺利进行。 它应该更简单,但我无法弄清楚发生了什么以及为什么会发生这种情况。

1 个答案:

答案 0 :(得分:0)

将您的单元格类修改为

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,如图所示

希望有所帮助