UICollectionView单元格固定宽度和动态高度使用swift中的约束

Khu*_*iOS 6 constraints ios uicollectionview swift

我有一个 collectionview 和一个单元格,里面有一个基于其内容的固定宽度和动态高度。我正在使用自动布局约束,我的代码如下。

我已经尝试在单元格内和视图内设置所有类型的自动约束。

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 5
        }

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

            cell.lbl_text.text = "djs sdfs sdfs dsfsfd gdgfd dfgd df "

            return cell

        }



        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.

            if let flowLayout = coll_main?.collectionViewLayout as? UICollectionViewFlowLayout {
                flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize

            }



    }

In cell class method:
override func awakeFromNib() {
        super.awakeFromNib()
        self.contentView.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight]
    }

    override func layoutSubviews() {
        self.layoutIfNeeded()
    }
Run Code Online (Sandbox Code Playgroud)

我得到了单元格宽度修复,而我没有设置那个宽度。这个问题如何解决?

这里截图。

在此处输入图片说明 在此处输入图片说明

jam*_*kid 9

您需要确保您的 CollectionViewEstimate Size设置None为 。


小智 2

您可以使用collectionView委托

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width:, height:)
}
Run Code Online (Sandbox Code Playgroud)

为此你需要扩展UICollectionViewDelegateFlowLayout