UICollectionView:AutoSizing单元格,增加按钮的高度

时间:2018-04-04 09:36:53

标签: ios uicollectionview uibutton autolayout uicollectionviewcell

目前,我的代码如下:

class MyClass: UICollectionViewCell {
  override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
    let targetSize = CGSize(width: layoutAttributes.frame.width, height: 0)
    let autoLayoutSize = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow)
    let autoLayoutFrame = CGRect(origin: autoLayoutAttributes.frame.origin, size: autoLayoutSize)
    autoLayoutAttributes.frame = autoLayoutFrame
    return autoLayoutAttributes
  }

  lazy var button = MyCustomButtonWithAppliedStyles()

  override init(frame: CGRect) {
    super.init(frame: frame)
    contentView.addSubview(button)
    contentView.backgroundColor = .white
    button.snp.makeConstraints { (make) in
      make.leading.trailing.equalTo(contentView.layoutMarginsGuide)
      make.height.equalTo(contentView.snp.height).dividedBy(2)
      make.centerY.equalToSuperview()
    }
  }
}

导致以下结果:

Current result

我想指定按钮的高度要大一些。 以下是我想要实现的结果: Goal

我可以通过添加一个约束来获得它:

make.height.equalTo(44)

问题是我收到了AutoLayout错误消息:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x6040002948c0 h=--& v=--& UIView:0x7fbc246207d0.height == 50   (active)>",
    "<SnapKit.LayoutConstraint:0x6040000bdca0@ListItemButtonCell.swift#31 SelfCare.MyCustomButtonWithAppliedStyles:0x7fbc24621f10.height == 44.0>",
    "<SnapKit.LayoutConstraint:0x6040000bdbe0@ListItemButtonCell.swift#29 SelfCare.MyCustomButtonWithAppliedStyles:0x7fbc24621f10.height == UIView:0x7fbc246207d0.height * 0.5>"
)

如何修复此错误?如果我已经知道单元格和按钮的所需高度,但是想要在其余的UICollectionViewCells上使用AutoSizing ,那么调试此问题或重写布局代码的方向可能是什么?

1 个答案:

答案 0 :(得分:0)

我通过设置contentEdgeInsets属性获得了预期的结果。

以下是我用完的配置代码:

button.contentEdgeInsets = UIEdgeInsets(top: 15, left: 0, bottom: 15, right: 0)
button.snp.makeConstraints { (make) in
  make.leading.trailing.equalTo(contentView.layoutMarginsGuide)
  make.height.equalTo(contentView.snp.height).dividedBy(2)
  make.centerY.equalToSuperview()
}

仍然,单元格和按钮高度都没有固定,可以更改,即当用户更改其字体首选项(DynamicType)时,问题仍然是打开的。