(1) 在viewcontroller里创建网格
import UIKit
class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{
var readID = "readID"
var flowlayout = UICollectionViewFlowLayout()
var collection: UICollectionView?
var collecArr=[News]()
// var collecArr = ["3","1","2"]
override func viewDidLoad() {
super.viewDidLoad()
let urlStr = "http://api.jisuapi.com/news/get"
let par : [String:Any] = [
"channel" : "头条",
"appkey" : "de394933e1a3e2db"
]
NetworkTools.sharedInstance.request(.GET, urlString: urlStr, parameters: par) { (result, error) in
guard error == nil else{
return
}
guard let jsonDict = result else{
return
}
let dict = jsonDict as! NSDictionary
let resultDict = dict.value(forKey: "result") as! NSDictionary
let listArray = resultDict.value(forKey: "list") as! NSArray
for item in listArray{
let dic = item as! NSDictionary
let oneNew = News()
oneNew.title = dic.value(forKey: "title") as! String
oneNew.content = dic.value(forKey: "content") as! String
oneNew.pic = dic.value(forKey: "pic") as! String
self.collecArr.append(oneNew)
}
self.collection?.reloadData()
}
// 设置网格的大小
flowlayout.itemSize = CGSize(width:self.view.frame.size.width/4, height: 100)
//设置最小行间距
flowlayout.minimumLineSpacing = 1
flowlayout.headerReferenceSize = CGSize(width: self.view.frame.size.width, height: 50)
flowlayout.footerReferenceSize = CGSize(width: self.view.frame.size.width, height: 50)
//设置最小列间距
flowlayout.minimumInteritemSpacing = 40
//设置分区缩进量
flowlayout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 20, right: 10)
// 设置滚动方向
flowlayout.scrollDirection = UICollectionViewScrollDirection.vertical
// 网格对象
collection = UICollectionView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) , collectionViewLayout: flowlayout)
// 设置代理协议
collection?.delegate = self
collection?.dataSource = self
collection?.backgroundColor = UIColor.white
collection?.register(NewsCollectionViewCell .self, forCellWithReuseIdentifier: readID)
collection?.register(HeaderCollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
collection?.register(FootCollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "foot")
// 添加网格
self.view .addSubview(collection!)
}
// 实现网格的协议代理
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// return collecArr.count
return collecArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 重用cell
let cell:NewsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: readID, for: indexPath) as! NewsCollectionViewCell
let model:News = self.collecArr[indexPath.item]
cell.titleLabel.text = model.title
cell.imageView.sd_setImage(with: URL(string: model.pic), completed: nil)
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
if kind == "UICollectionElementKindSectionHeader" {
let head:HeaderCollectionReusableView = collection?.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! HeaderCollectionReusableView
head.label.text = "asdasdqwq"
return head
}
let foot:FootCollectionReusableView = collection?.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "foot", for: indexPath) as! FootCollectionReusableView
foot.label.text = "caonima"
return foot
}
}
(2) 创建自定义cell继承UIcollectionviewcell
import UIKit
class NewsCollectionViewCell: UICollectionViewCell {
var titleLabel = UILabel()
var imageView = UIImageView()
var button = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.frame = CGRect(x: 0, y: 0, width: self.contentView.frame.size.width, height: self.contentView.frame.size.height * 0.25)
self.addSubview(titleLabel)
imageView.frame = CGRect(x: 0, y: titleLabel.frame.size.height, width: self.contentView.frame.size.width, height: self.contentView.frame.size.height - titleLabel.frame.size.height)
self.addSubview(imageView)
button.frame = CGRect(x: (imageView.frame.size.width - 40) / 2, y: (imageView.frame.size.height - 40) / 2, width: 40, height: 40)
// button.backgroundColor = .green
button.setImage(UIImage(named: "播放"), for: .normal)
self.imageView.addSubview(button)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// (3)创建一个继承于viewcontroller的类用来头部视图
import UIKit
class HeaderCollectionReusableView: UICollectionReusableView {
lazy var label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 50))
override init(frame: CGRect) {
super.init(frame: frame)
label.backgroundColor = .red
label.textAlignment = .center
self.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
(4) 创建一个继承于viewcontroller的类用来做尾部视图
import UIKit
class FootCollectionReusableView: UICollectionReusableView {
lazy var label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 50))
override init(frame: CGRect) {
super.init(frame: frame)
label.backgroundColor = .red
label.textAlignment = .center
self.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
(5) 创建一个nsobject的类用来做model
import UIKit
class News: NSObject {
var time:String = ""
var title:String = ""
var pic:String = ""
var content:String = ""
var weburl:String = ""
}