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

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

只适应布局,负担选择框

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

UICollectionView:设定边界位置

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

collectionView

cell-label

关联代理,实现代理方法。

二、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不对
复用之后的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

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值