设置收集视图单元格的动态宽度时出现问题

时间:2019-02-04 07:33:07

标签: ios swift uicollectionview uicollectionviewdelegateflowlayout

我正在尝试动态设置集合视图单元格的宽度。最初,它没有按预期方式渲染。但是,当我点击该单元格时,它会根据需要进行调整。这是我编写的代码:

代码

import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

    @IBOutlet weak var collView: UICollectionView!


    var tasksArray = ["To Do", "SHOPPING","WORK"]
    var selectedIndex = Int()

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout = collView?.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = UICollectionViewFlowLayout.automaticSize
        layout.estimatedItemSize = CGSize(width: 93, height: 40)
        // Do any additional setup after loading the view, typically from a nib.
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tasksArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
        cell.lblName.text = tasksArray[indexPath.row]
        if selectedIndex == indexPath.row
        {
            cell.backgroundColor = UIColor.lightGray
        }
        else
        {
            cell.backgroundColor = UIColor.white
        }
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = cell.frame.height / 2
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedIndex = indexPath.row
        self.collView.reloadData()
    }
}

在这里,我在点击之前和之后都附加了两个图像,以便您轻松理解

[![这是我点击之前的图像

this is after tapping on cell its give me perfect result on cell] 2] 2

所以请告诉我我的代码有什么问题

3 个答案:

答案 0 :(得分:1)

/sys/sys覆盖make buildkernel函数内部,此单元格有机会指示其首选属性,包括尺寸,这是我们使用自动布局计算得出的。

CollectionViewCell

答案 1 :(得分:0)

我发现了一个快速4.2的小技巧

对于动态宽度和固定高度:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let label = UILabel(frame: CGRect.zero)
    label.text = textArray[indexPath.item]
    label.sizeToFit()
    return CGSize(width: label.frame.width, height: 32)
}

答案 2 :(得分:0)

很明显,必须使用sizeForItemAt流布局委托才能传递动态宽度。但是棘手的部分是根据文本计算单元格的宽度。只要有字体,就可以实际计算出文本的宽度。

让我们介绍一些扩展名,这将对我们有帮助

StringExtensions.swift

extension String {

    public func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect,
                                        options: .usesLineFragmentOrigin,
                                        attributes: [.font: font], context: nil)

        return ceil(boundingBox.width)
    }
}

如果我提供字符串的高度和字体,则此方法让我们知道字符串的宽度。然后在sizeForItem内部使用它,如下所示

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height = 40
    let text = YOUR_TEXT
    let width = text.width(withConstrainedHeight: height, font: Font.regular.withSize(.extraSmall)) + EXTRA_SPACES_FOR_LEFT_RIGHT_PADDING
    return CGSize(width: width, height: height)
}