您的位置:首页 > 移动开发 > Swift

Swift 使用SnapKit实现 UICollectionViewCell 高度自适应

2017-12-19 11:32 2071 查看

问题

在我们的日常开发中,经常会使用到UICollectionViewCell、UITableViewCell的自适应。

解决方案

之前的MVC开发中,使用SnapKit 处理UICollectionViewCell 高度自适应的问题后,一直想抽时间整理一下,下面就用部分的代码,解释一下 我这边处理的思路。

Controller

//
//  TaskVC.swift
//  BossClient
//
//  Created by qingxun on 2017/12/12.
//  Copyright © 2017年 吕陈强. 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:-滚动视图
lazy var collectionView:UICollectionView = { [unowned self] in
let flow = UICollectionViewFlowLayout();
//垂直滚动
flow.scrollDirection = .vertical
//最小行间距(当垂直布局时是行间距,当水平布局时可以理解为列间距)
flow.minimumLineSpacing = NEWHEIGHT(10);
//两个单元格之间的最小间距
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 = "任务列表";

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:-滚动视图的代理事件
extension TaskVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

//集合视图的协议方法 dataSource
/**
返回每个分组有几个数据
*/
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{

return self.dataArr.count;
}
/**
返回有几个分组
*/
func numberOfSections(in collectionView: UICollectionView) -> Int
{

return 1;
}
/**
返回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;

}

//选中的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 © 2017年 吕陈强. 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 = "黄君";

return lab;
}()

fileprivate lazy var messageLab:UILabel = {

let lab = UILabel()
lab.textColor = kTextPlaceHolderColor;
lab.font = FONT(14);
lab.text = "捐献爱心"
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 = "五分钟前"
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:初始化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);
}
}

}


在上面的代码中,我们在Controller中,











Model中就没有什么介绍的了。

在View中,介绍几点就是







最终的UI效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐