首先了解一下网络请求框架Alamofire,用SwiftyJSON进行JSON转换。
布局用xib,很简单,拖一拖,添加一下约束就好了
这行是Get请求
//url:我们请求的地址,
//parameters:我们请求的参数
//responseJSON得到返回数据
Alamofire.request(url,parameters:params).responseJSON{(response) in
//如果是错误就返回
guard response.result.isSuccess else{
return
}
//response.result.value是全部字符串内容
if let value = response.result.value{
//JSON转换
let json = JSON(value)
//判断,不是直接返回
guard json["message"] == "success" else{
return
}
//判断data是不是数组对象
if let data = json["data"].arrayObject{
var concerns = [MyConcern]()
for data in datas{
把JSON转成对象
let myCellModel = MyConcern.deserialize(from: data as? NSDictionary)
数组添加
concerns.append(myCellModel!)
}
}
}
}
接下来是 UICollectionView
@IBOutlet weak var collectionView: UICollectionView!
//数据源
var myConcerns = [MyConcern](){
didSet{
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
//设置布局属性
collectionView.collectionViewLayout = MyConcernFlowLayout()
//设置代理
collectionView.delegate = self
//数据源
collectionView.dataSource = self
//注册自己的组件
collectionView.ym_registerCell(cell: MyConcernCell.self)
}
//这是一个MyCell是UITableViewCell
//代理
//数据代理
extension MyCell:UICollectionViewDelegate,UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return myConcerns.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.ym_dequeueReusableCell(indexPath: indexPath) as MyConcernCell
//这里传递数据
cell.myConcern = myConcerns[indexPath.item]
return cell
}
}
//Collection是布局
class MyConcernFlowLayout:UICollectionViewFlowLayout{
override func prepare() {
itemSize = CGSize(width: 58, height: 74)
minimumLineSpacing = 0
minimumInteritemSpacing = 0
sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
scrollDirection = .horizontal
}
}
组件之间传递数据
//这里是传递数据给子Cell,也就是UICollectionViewCell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
....
//冒号省略的是从内存中获取的cell,也就是UICollectionViewCell
//这里的myConcern,是在子cell定义的model
cell.myConcern = myConcerns[indexPath.item]
....
}
在子cell里面接收
//定义一个变量就可以接收到了
var myConcern:MyConcern?{
didSet{
}
}
设置图片的圆角
layer.cornerRadius 20
layer.masksToBounds true