Passing data to collectionViewCell

I'm want to use some custom struct in my collection view cell. I get the data from my API service and trying to pass it to my custom collection view cell.

I found couple answers but I still couldn't figure out how to do

Here is where I get the actual data:

    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()
}

Also here I'm trying to pass data to the cell:

    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
}

The actual problem is starting into my cell class

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)

}

}

As you guys can see in the code It's going well until my collection view cell. It should be a lot more simple but I couldn't figure out what's going on and Why its happening.

Upvotes: 1

Views: 2119

Answers (1)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

Modify your cell class as

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
 }
}

finally

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
}

Look for (cell as! BaseFormCollectionViewCell).configure() in cellForItemAt thats how u trigger the UI configuration of cell after passing data to cell in statement above it.

Quite frankly u can get rid of didSet and relay on configure as shown

Hope it helps

Upvotes: 2

Related Questions