将数据传递给 collectionViewCell
Passing data to collectionViewCell
我想在我的集合视图单元格中使用一些自定义结构。我从我的 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
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修改为
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
}
在 cellForItemAt
中查找 (cell as! BaseFormCollectionViewCell).configure()
这就是你如何在将数据传递到单元格上方的语句后触发单元格的 UI 配置。
坦率地说,您可以摆脱 didSet
并继续 configure
,如图所示
希望对您有所帮助
我想在我的集合视图单元格中使用一些自定义结构。我从我的 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
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修改为
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
}
在 cellForItemAt
中查找 (cell as! BaseFormCollectionViewCell).configure()
这就是你如何在将数据传递到单元格上方的语句后触发单元格的 UI 配置。
坦率地说,您可以摆脱 didSet
并继续 configure
,如图所示
希望对您有所帮助