UICollectionView使用storyBoard完成设置自动布局,并附带简单选择功能

UICollectionView使用storyBoard完成设置自动布局,并附带简单选择功能

一、storyBoard实现UICollectionView,并添加UICollectionViewCell。

UICollectionView:设定边界位置

TextLabelCell(UICollectionViewCell):
backView-实现选择背景框,边界与cell相同
contentLbl-内容显示,设置居中显示,不设定大小,不设定上下左右位置。

关联代理,实现代理方法

二、UICollectionView设置自适应大小

实现代理方法中不需要指定cell大小,只需要三个代理
numberOfSections
numberOfItemsInSection
cellForItemAt indexPath
实现正常功能即可。

//设置为自适应方式 确定cell size,size不能为空,可以随意设置一个
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width: 20,height: 20)

三、修改UICollectionViewCell属性

在TextLabelCell重写preferredLayoutAttributesFitting方法,这里可以自定义设置cell大小

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        let attributes = super.preferredLayoutAttributesFitting(layoutAttributes)
        attributes.frame = CGRect(x: 0,y: 0,width:Nsstring(string: contentLbl.text!).size(attributes: [NSFontAttributeName:contentLbl.font]).width+40,height: 40)
        //计算cellSize,当前要求高度固定40,宽度自适应,现在根据字符串求出所需宽度+42,contentLabel相对cell左右各有20的空间
        //根据具体需求作灵活处理
        return attributes

}

如果只设置UICOllectionViewFlowLayout属性,不重写cell方法,在复用的时候会出现问题导致所求的size不对

四、最终结果

完成上面主要两步就能实现自适应大小功能,另外因为一个小需求,做一个多项选择的处理,下面给出完整代码

ViewController.swift

class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    var selectedindexArray:Array = Array<IndexPath>()

    var dataArray:Array = Array<String>()

    @IBOutlet var collectionView: UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
        //设置为自适应方式 确定cell size
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width: 20,height: 20)

        //设置横向间距
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).minimumInteritemSpacing = 5

        //设置纵向间距-行间距
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).minimumLinespacing = 20

        dataArray.append("第一个第二个第三个")
        for _ in 0 ..< 100 {
            let index = arc4random()%5;
            dataArray.append("\(index*index*index*500 + 8)")
        }

    }

    // MARK: UICollectionView DataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1;
    }
    func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return dataArray.count;
    }


    func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TextLabelCell",for: indexPath) as! TextLabelCell

        cell.contentLbl.text = dataArray[indexPath.row]
        cell.cellStatusWithSelected(selected: ((selectedindexArray.index(of: indexPath) != nil)))

        return cell
    }

    func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! TextLabelCell
        if let i = selectedindexArray.index(of: indexPath) {
            print("selected:\(i)")
            selectedindexArray.remove(at: i)
            cell.cellStatusWithSelected(selected: false)
        } else {
            selectedindexArray.append(indexPath)
            cell.cellStatusWithSelected(selected: true)
        }
    }

    //保存
    @IBAction func saveButtonClicked(_ sender: Any) {
        for index in selectedindexArray {
            print(dataArray[index.row])
        }
    }

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


}

TextLabelCell.swift

class TextLabelCell: UICollectionViewCell {

    @IBOutlet var contentLbl: UILabel!
    @IBOutlet var backView: UIView!

    override func awakeFromNib() {
        backView.layer.borderWidth = 1;
        backView.layer.borderColor = UIColor.lightGray.cgColor;
    }


    func cellStatusWithSelected(selected:Bool) {
        if selected {
            backView.layer.borderColor = UIColor.red.cgColor;
            contentLbl.textColor = UIColor.red;
        } else {
            backView.layer.borderColor = UIColor.lightGray.cgColor;
            contentLbl.textColor = UIColor.lightGray;
        }
    }

    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        let attributes = super.preferredLayoutAttributesFitting(layoutAttributes)
        attributes.frame = CGRect(x: 0,y: 0,width:Nsstring(string: contentLbl.text!).size(attributes: [NSFontAttributeName:contentLbl.font]).width+40,height: 40)
        //计算cellSize,当前要求高度固定40,宽度自适应,现在根据字符串求出所需宽度+42,contentLabel相对cell左右各有20的空间
        //根据具体需求作灵活处理
        return attributes

    }
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...