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

查看:105
本文介绍了ios - 自定义的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 。

解决方案

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

这篇关于ios - 自定义的collectionCell无法自适应约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆