swift 自定义collectionView

使用习惯了OC编写代码,在下载了一个swift编写的demo,模仿下来发现swift语法集百家之所长。下面就是对用swift编写的自定义collectionView进行阐述。熟悉MVC的同学应该很容易理解,下面就是用MVC进行编写。

M
定义一个Model用来数据持久化。这里使用了一个数据解析的第三方SwiftJSON.

import UIKit
import SwiftyJSON
class ProgrameModel: NSObject {
    var game_icon : String? // 定义变量
    var game_name : String?
    init(dic: JSON) {
        super.init()
        self.game_icon = dic["game_icon"].string
        self.game_name = dic["game_name"].string
    }
}

V
自定义collectionViewCell,按照美工给的效果图,进行设计。自定义一个collectionViewCell,所以生成的都按照这个模型给你创建出来,一劳永逸。下面是创建一个自定义collectionViewCell的方法

import UIKit
// 自定义cell继承自UICollectionViewCell
class ProgrameCell: UICollectionViewCell {

    // 定义自定义集合视图cell控件
    var img = UIImageView()
    var name = UILabel()

    // set一个model 这个model可以是控制器传过来
    func sendModel(model : ProgrameModel) {
    // 这里是给图片赋值使用了一个第三方
        img.sd_setImage(with: URL.init(string: model.game_icon!), placeholderImage: UIImage.init(named: "logo"))
        // label赋值
        name.text = model.game_name
    }

    // 设置cell的frame
   override init(frame: CGRect) {
        super.init(frame: frame)

    // 设置img frame
    img = UIImageView.init(frame: .init(x: 0, y: 0, width: self.contentView.width, height: self.contentView.width))
    self.contentView.addSubview(img)

    //设置label
    name = UILabel.init(frame: .init(x: 0, y: img.bottom, width: img.width, height: 21))
    name.textAlignment = .center
    name.font = UIFont.systemFont(ofSize: 14)
    self.contentView.addSubview(name)

    // 下面那条黄色线
    let line = UIView.init(frame: .init(x: 0, y: name.bottom, width: img.width, height: 1))
    line.backgroundColor = UIColor.orange
    self.contentView.addSubview(line)
    }
    // 重写系统方法使用 override ,下面方法是系统自定生成
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

到这里创建好了Model和View。下面就是在控制器里面使用。

C

import UIKit
import SwiftyJSON // 导入第三方framework
class ViewController: UIViewController {
// 创建一个数组用来存放请求的数据
    var programeArray = Array<Any>()

    // 使用懒加载集合视图
    lazy var collevtionView : UICollectionView = {
    // 创建UICollectionViewFlowLayout
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = .init(width: (UIScreen.main.bounds.size.width - 40) / 3, height: (UIScreen.main.bounds.size.width - 40) / 3 + 30)
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.sectionInset = .init(top: 10, left: 10, bottom: 0, right: 10)
       // 创建 UICollectionView
        let collection = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), collectionViewLayout: layout)
        collection.delegate = self
        collection.dataSource = self
        collection.backgroundColor = UIColor.white
        collection.register(ProgrameCell.self, forCellWithReuseIdentifier: "ProgrameCell")
        return collection
    }()


    // 获取网络数据
    func getProgrameDate()  {
        NetRequest.sharedInstance.getRequest(urlString: "http://www.douyutv.com/api/v1/game?aid=ios&auth=3f252c3294b31a61fbdd890a45609549&client_sys=ios&time=", params: ["" : ""]) { (response) in
            let json = JSON(response)
            for (_,subJson) : (String, JSON) in json["data"]{
                let model = ProgrameModel.init(dic : subJson)
                self.programeArray.append(model)
                self.collevtionView.reloadData()
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(self.collevtionView)
        getProgrameDate()
    }
}

// 用这种方式去实现collectionView的代理方法比较方便
extension ViewController :UICollectionViewDelegate,UICollectionViewDataSource{

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      return self.programeArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProgrameCell", for: indexPath) as! ProgrameCell
        cell.sendModel(model: programeArray[indexPath.item] as! ProgrameModel)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item)
    }

}

到此就是实现一个简单的集合视图的全部,这里用到了swift和oc混编,因为用的还是oc里面的那些第三方,其中网络请求和UIView扩展都写成了工具类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值