Swift CollectionView 基础进阶用法

392 阅读1分钟

CollectionView自定义布局

import Foundation
import RxSwift
import UIKit
class ShopCollectionView: UIView {
 
 weak var actionVC: UIViewController?
 
 open var list = [UserModel](){
     didSet{
         collectionView.reloadData()
     }
 }

 lazy var collectionView: UICollectionView = {
   
     // 设置布局
     let layout = UICollectionViewFlowLayout()
     layout.minimumLineSpacing = 12
     layout.minimumInteritemSpacing = 12
     // 备注: 这个 20 是VC最外面布局调用时的
     layout.itemSize = CGSize(width:(Screen.width - 16*2 - 12 - 20)/2, height: 200)
     layout.scrollDirection = .vertical
     layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
     
     let c = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height), collectionViewLayout: layout)
     c.collectionViewLayout = layout
     c.showsHorizontalScrollIndicator = false
     c.backgroundColor = .clear
     c.delegate = self
     c.dataSource = self
     // 拓展一下:如需要画这个外边框,代码如下
     c.layer.borderWidth = 1
     c.layer.borderColor = UIColor.white.cgColor
     c.layer.cornerRadius = 5
     
     return c
 }()
 
 override func layoutSubviews() {
     super.layoutSubviews()
     collectionView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
     
 }
 
 override init(frame: CGRect) {
     super.init(frame: frame)
     addSubview(collectionView)
 }
 
 required init?(coder: NSCoder) {
     super.init(coder: coder)
 }
 
}

//MARK: UICollectionView 代理
extension ShopCollectionView: UICollectionViewDelegate,UICollectionViewDataSource {

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     return 10 
 }
 
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     
     let cell = collectionView.dequeueReusableCell(index: indexPath) as  ShopCell
     return cell
     
 }

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
     /// 点击跳转

 }
}

最后:外面VC调用如下

 override func viewDidLoad() {
     super.viewDidLoad()
    /// 商店布局
    let shopView = ShopCollectionView()
     let W:CGFloat = Screen.width - 20
     let H:CGFloat = Screen.height - 125
     shopView.frame = CGRect(x: 10, y: 130, width:W  , height: H )
     self.view.addSubview(shopView)
}

预告:下节内容更新是VC层 的UI 结构如何优美布局,若有兴趣敬请关注