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

import UIKit
import SnapKit

class FeatureCollectionViewCell: UICollectionViewCell {
  var itemTitleLabel: UILabel!
  
  // MARK: - Initializer & Release
  override init(frame: CGRect) {
    print("FeatureCollectionViewCell was initialized")
    super.init(frame: frame)
    setupViews()
    setupConstraints()
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) 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.addSubview(itemTitleLabel)
  }
  
  override func setupConstraints() {
    itemTitleLabel.snp_makeConstraints { (make) in
      make.top.equalTo(contentView).offset(8)
      make.centerX.equalTo(contentView)
    }
  }
  // MARK: - Private Method
  func configureCell(title: String, image: UIImage) {
    itemTitleLabel.text = title
  }
  
  override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    let attributes = super.preferredLayoutAttributesFittingAttributes(layoutAttributes)
    let newSize = contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
    attributes.frame.size = newSize
    
    return attributes
  }
  
}

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

阅读 4.7k
1 个回答

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题