自定义的collectionCell无法自适应约束

import UIKit
import SnapKit class FeatureCollectionViewCell: UICollectionViewCell { var itemTitleLabel: UILabel! // MARK: - Initializer & Release override initframe: CGRect { print"FeatureCollectionViewCell was initialized" super.initframe: frame setupViews setupConstraints } required init?coder aDecoder: NSCoder { fatalError"initcoder: has not been implemented" } deinit { print"FeatureCollectionViewCell was released" } // MARK: - Extension Method override func setupViews { contentView.backgroundColor = UIColor.grayColor itemTitleLabel = UILabel itemTitleLabel.translatesAutoresizingMaskIntoConstraints = false itemTitleLabel.text = "Test Test" contentView.addSubviewitemTitleLabel } override func setupConstraints { itemTitleLabel.snp_makeConstraints { make in make.top.equalTocontentView.offset8 make.centerX.equalTocontentView } } // MARK: - Private Method func configureCelltitle: String, image: UIImage { itemTitleLabel.text = title } override func preferredLayoutAttributesFittingAttributeslayoutAttributes: UICollectionViewLayoutAttributes -> UICollectionViewLayoutAttributes { let attributes = super.preferredLayoutAttributesFittingAttributeslayoutAttributes let newSize = contentView.systemLayoutSizeFittingSizeUILayoutFittingCompressedSize attributes.frame.size = newSize return attributes } }

我是想通过 systemLayoutSizeFittingSize 获取 contentViewsize ( label的宽高,再加上 label 对于顶部的距离约束),但是却获取的一直是0, 0。
PS:没有用 StoryBoard/Xib 。

你的约束条件不够,必须要有四个要素。

发表评论

电子邮件地址不会被公开。 必填项已用*标注