约束问题

时间:2018-03-22 01:42:28

标签: ios swift uicollectionview constraints

所以我有一个设置为在其中包含collectionView的单元格。该单元格的高度在此函数中给出。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if indexPath.section == 0 {
         return CGSize(width: view.frame.width, height: 300)
    }
    return CGSize(width: view.frame.width, height: 280)

}

在这个单元格的类中,我创建了一个collectionView,并再次创建了一个单元格集合。

@objc func setupViews(){
    backgroundColor = .red
    addSubview(categoryCollectionView)
    addSubview(sectionNameLabel)
    sectionNameLabel.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 14, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
            categoryCollectionView.anchor(top: sectionNameLabel.bottomAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
            categoryCollectionView.delegate = self
            categoryCollectionView.dataSource = self
            categoryCollectionView.showsHorizontalScrollIndicator = false
    categoryCollectionView.register(CategoryEventCell.self, forCellWithReuseIdentifier: cellID)

}

每个单元格都有一个背景图像和一个位于图像下方的标题。然而,文本总是有点切断。我目前的限制在这里

@objc func setupViews(){
    backgroundColor = .clear
    setCellShadow()
    addSubview(backgroundImageView)
    addSubview(eventNameLabel)
    backgroundImageView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 9, paddingRight: 0, width: 0, height: 0)
    eventNameLabel.anchor(top: backgroundImageView.bottomAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)

}

我如何更改约束或文本/元素大小以确保一切都适合?

我目前的观点是这样的

enter image description here

1 个答案:

答案 0 :(得分:1)

您将图像固定在其单元格的底部,标签上没有说明如何放入。相反,您应该将图像固定到标签的顶部,标签&# 39;在电池底部的底部。像这样的可视化格式语言:[image]-[label]-|。您还需要编辑backgroundImageView的内容压缩阻力。

以下是固定版本,其中标签会使图像的高度向上缩小以适应:

@objc func setupViews(){
    backgroundColor = .clear
    setCellShadow()
    addSubview(backgroundImageView)
    addSubview(eventNameLabel)
    // ensure the image compresses, not the eventNameLabel, by lowering its priority
    backgroundImageView.setContentCompressionResistancePriority(UILayoutPriority(600), for: .vertical)
    backgroundImageView.anchor(top: topAnchor, left: leftAnchor, bottom: eventNameLabel.topAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
    eventNameLabel.anchor(top: backgroundImageView.bottomAnchor, left: leftAnchor, bottom: bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
}