【发布时间】:2018-03-17 08:21:36
【问题描述】:
我的 json 数据就是这样,我使用 alamofire 加载数据,使用 objectmapper 进行映射。我只是尝试解析 json 数据并将其显示在 CollectionView 上。但是我遇到了错误。
这是我的视图控制器
import UIKit
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return schedules?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = UICollectionViewCell()
cell.textLabel?.text = schedules?[indexPath.row].title
}
@IBOutlet weak var collectionViewData: UICollectionView!
var schedules: [Schedule]?
override func viewDidLoad() {
super.viewDidLoad()
collectionViewData.dataSource = self
collectionViewData.delegate = self
loadData()
}
func loadData() {
let jsonDataUrl = "https://jsonplaceholder.typicode.com/posts"
Alamofire.request(jsonDataUrl).responseJSON { response in
self.schedules = Mapper<Schedule>().mapArray(JSONObject: response.result.value)
self.collectionViewData.reloadData()
}
}
}
这是我的映射计划文件代码。
import Foundation
import ObjectMapper
import AlamofireObjectMapper
class Schedule: Mappable {
var userId: String
var id: String
var title: String
var body: String
required init?(map: Map) {
userId = ""
id = ""
title = ""
body = ""
}
func mapping(map: Map) {
userId <- map["userId"]
id <- map["id"]
title <- map["title"]
body <- map["body"]
}
}
当我尝试运行它时,我收到了这样的错误:“UICollectionViewCell”类型的值没有成员“textLabel”
我尝试将“textLabel”添加到视图控制器,但它不起作用。我应该为 CollectionView 添加一个新类吗?
【问题讨论】:
-
UICollectionViewCell没有您需要创建的任何textLabel属性。您应该首先按照任何教程了解如何使用collectionView,建议您访问raywenderlich.com/136159/…
标签: ios swift uicollectionview alamofire objectmapper