Swift uses SnapKit to realize highly adaptive UICollectionViewCell

Keywords: Swift

problem

In our daily development, we often use the adaptation of UICollectionViewCell and UITableViewCell.

Solution

In the previous MVC development, after using SnapKit to deal with the highly adaptive problem of UICollectionViewCell, I always wanted to take the time to sort it out. Next, I will use some code to explain my handling ideas.

Controller

//
//  TaskVC.swift
//  BossClient
//
//  Created by qingxun on 2017/12/12.
//  Copyright © 2017 Lu chenqiang. All rights reserved
//

import UIKit

class TaskVC: BaseViewController {



    fileprivate var dataArr:[TaskItemModel] = {
        var data = [TaskItemModel]()

        let model1 = TaskItemModel()
        model1.name = "123"
        model1.content = "123123123123123123123123123123123123123123123123123123123123123123";
        data.append(model1);


        let model2 = TaskItemModel()
        model2.name = "5446"
        model2.content = "3453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453451231345345345345345345345";
        data.append(model2);




        let model3 = TaskItemModel()
        model3.name = "123"
        model3.content = "123123123123123123123123123123123123123123123123123123123123123123";
        data.append(model3);


        let model4 = TaskItemModel()
        model4.name = "5446"
        model4.content = "3453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453453451231345345345345345345345";
        data.append(model4);


        let model5 = TaskItemModel()
        model5.name = "qweqwe"
        model5.content = "qweqweqwedasdqwewqeasdasdwqeqweasdasdqweqweasdasdweqweadasdqweqweasdasdqweqweasdadwqeqwasdasdadasdasdweqweqweqasdasdasdasdasdweqeqweqasd";
        data.append(model5);

        return data;
    }()

    //MARK: - scroll view
    lazy var collectionView:UICollectionView = { [unowned self] in
        let flow = UICollectionViewFlowLayout();
        //Vertical scrolling
        flow.scrollDirection = .vertical
        //Minimum row spacing (row spacing when vertical layout, column spacing when horizontal layout)
        flow.minimumLineSpacing = NEWHEIGHT(10);
        //Minimum space between two cells
        flow.minimumInteritemSpacing = NEWWIDTH(10);

        flow.estimatedItemSize = CGSize(width: kScreenW, height: NEWHEIGHT(150));
//        flow.itemSize = 

        let collectionView = UICollectionView(frame: M_RECT(0, y: NEWHEIGHT(100), w: kScreenW, h: kScreenH - 64 - NEWHEIGHT(100)), collectionViewLayout: flow);
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.isScrollEnabled = true;
        //        collectionView.alwaysBounceVertical = false;
//        collectionView.contentInset = UIEdgeInsets(top: 0, left:0, bottom: NEWHEIGHT(20), right: NEWWIDTH(0));




        collectionView.showsVerticalScrollIndicator = false;
        collectionView.showsHorizontalScrollIndicator  = false;
        collectionView.backgroundColor = UIColor.white;
        collectionView.register(TaskItemCell.self, forCellWithReuseIdentifier: "TaskItemCell");

        return collectionView;
        }();

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.title = "task list";

        setupUI();
        // Do any additional setup after loading the view.
    }




    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




}


extension TaskVC{
    fileprivate func setupUI(){

        self.view.addSubview(self.collectionView);
        self.collectionView.snp.makeConstraints { (make) in
            make.left.right.top.bottom.equalTo(self.view);
        }

    }

}



//MARK: - agent event for scroll view
extension TaskVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

    //Protocol method dataSource of collection view
    /**
     Return how many data per group
     */
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{

        return self.dataArr.count;
    }
    /**
     There are several groups to return
     */
    func numberOfSections(in collectionView: UICollectionView) -> Int
    {

        return 1;
    }
    /**
     Return to cell
     */
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {

        let model = self.dataArr[indexPath.row];
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TaskItemCell", for: indexPath) as! TaskItemCell;

        cell.valueData = model;
        return cell;

    }


    //Selected cell
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {


    }


//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
//    {
//        
//        return  CGSize(width: kScreenW, height:NEWHEIGHT(150));
//    }   
}

Model

import UIKit
class TaskItemModel: BaseModel {
    var name:String = ""
    var content:String = ""
    var time:String = ""

}

View

//
//  TaskItemCell.swift
//  BossClient
//
//  Created by qingxun on 2017/12/18.
//  Copyright © 2017Lu chenqiang in. All rights reserved.
//

import UIKit

class TaskItemCell: UICollectionViewCell {


    var valueData:TaskItemModel! {
        didSet{


            self.nameLab.text = valueData.name;
            self.messageLab.text = valueData.content;


        }
    }


   fileprivate lazy var iconImageV:UIImageView = {
        let imageV = UIImageView()
        imageV.image = #imageLiteral(resourceName: "user_icon");

        return imageV;
    }()


   fileprivate lazy var nameLab:UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.black;
        lab.font = FONT(14);
        lab.text = "Huang Jun";

        return lab;
    }()

   fileprivate lazy var messageLab:UILabel = {

        let lab = UILabel()
        lab.textColor = kTextPlaceHolderColor;
        lab.font = FONT(14);
        lab.text = "Donate love"
        lab.textAlignment = .left
        lab.lineBreakMode = .byClipping;
        lab.numberOfLines = 0;
        //        lab.backgroundColor = UIColor.red
        return lab;
    }()



   fileprivate lazy var timeLab:UILabel = {
        let lab = UILabel()
        lab.textColor = kTextPlaceHolderColor;
        lab.font = FONT(22);
        lab.text = "Five minutes ago"
        lab.textAlignment = .right
        lab.lineBreakMode = .byClipping;

        return lab;
    }()



    fileprivate  lazy  var bottomLine:UIView = {
        let line = UIView()
        line.backgroundColor = kLineColor;
        return line;
    }()

    override init(frame: CGRect) {
        super.init(frame: frame);

                setupUI();

    }

    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {

     return super.preferredLayoutAttributesFitting(layoutAttributes);
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


}

//MARK: initialize UI
extension TaskItemCell{

    fileprivate func setupUI(){

        self.addSubview(self.iconImageV);
        self.iconImageV.snp.makeConstraints { (make) in
            make.leftMargin.equalTo(kLeftMargin);
            make.topMargin.equalTo(kTopMargin);
            make.width.height.equalTo(NEWWIDTH(80));

        }


        self.addSubview(self.nameLab);
        self.nameLab.snp.makeConstraints { (make) in
            make.left.equalTo(self.iconImageV.snp.right).offset(NEWWIDTH(20));
            make.top.equalTo(self.iconImageV.snp.top);
            make.height.equalTo(NEWHEIGHT(30));
            make.width.equalTo(NEWWIDTH(400));
        }


        self.addSubview(self.messageLab);
        self.messageLab.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.nameLab);
            make.top.equalTo(self.nameLab.snp.bottom).offset(NEWHEIGHT(10));
            make.height.greaterThanOrEqualTo(NEWHEIGHT(30));
            make.bottom.equalTo(self.snp.bottom).offset(-NEWHEIGHT(20));
        }


        self.addSubview(self.bottomLine);
        self.bottomLine.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(1);
        }
    }

}

In the above code, we are in the Controller,

There is no introduction in the Model.

In View, the introduction is

Final UI effect

Posted by SteveMT on Mon, 04 May 2020 16:46:26 -0700