将自定义UIView笔尖的宽度设置为其父CollectionViewCell

时间:2019-03-21 12:11:26

标签: ios swift uicollectionview xib nib

这就是我所拥有的:

具有2列的收藏视图,每列之间的距离相等。

每个单元均加载SmallCardView.xib。 SmallCardView包含一个正方形图像,下面带有一些文本。

问题:

我希望视图的宽度匹配其父视图(单元格)的宽度。比较屏幕尺寸可以最好地说明这一点

Screen size comparison

如上所示,两个屏幕上的单元格(紫色轮廓)大小正确,但SmallCardView保持相同大小

这是我的“集合视图控制器”中的代码:

viewDidLoad-

private let spacing: CGFloat = 20.0

override func viewDidLoad() {
    super.viewDidLoad()

    let layout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
    self.collectionView?.collectionViewLayout = layout
}

sizeForItemAt-

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let numberOfItemsPerRow: CGFloat = 2
    let spacingBetweenCells: CGFloat = 20

    let totalSpacing = (2 * self.spacing) + ((numberOfItemsPerRow - 1) * spacingBetweenCells) // Amount of total spacing in a row

    if let collection = self.collectionView {
        let width = (collection.bounds.width - totalSpacing)/numberOfItemsPerRow
        return CGSize(width: width, height: width * 1.2)
    } else {
        return CGSize(width: 0, height: 0)
    }
}

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以将具有约束的视图嵌入边缘,如下所示:

extension UIView {

    func makeEdges(to view: UIView, useMargins: Bool = false) -> [NSLayoutConstraint] {
        return [
            (useMargins ? layoutMarginsGuide.leftAnchor : leftAnchor).constraint(equalTo: view.leftAnchor),
            (useMargins ? layoutMarginsGuide.rightAnchor : rightAnchor).constraint(equalTo: view.rightAnchor),
            (useMargins ? layoutMarginsGuide.topAnchor : topAnchor).constraint(equalTo: view.topAnchor),
            (useMargins ? layoutMarginsGuide.bottomAnchor : bottomAnchor).constraint(equalTo: view.bottomAnchor)
        ]
    }

    func edges(to view: UIView, useMargins: Bool = false) {
        NSLayoutConstraint.activate(makeEdges(to: view, useMargins: useMargins))
    }
}

并将其用作:

let cardView = ...
cardView.translatesAutoresizingMaskIntoConstraints = false
let cell = ...
cell.contentView.addSubview(cardView)
cell.contentView.edges(to: cardView, useMargins: true)

答案 1 :(得分:0)

首先从情节提要中获取collectionview。设置它的约束,如下所示:-

  1. 集装箱的领先空间-20
  2. 将空间拖至集装箱-20
  3. 容器的顶部空间-20
  4. 容器的底部空间-20

然后选择collectionview并删除默认值为10的行填充。因此,将其更新为20。因此,cellpadding的每一侧应为10。

然后转到viewcontroller文件并添加所有3个委托  1. UICollectionViewDelegate  2. UICollectionViewDataSource  3. UICollectionViewDelegateFlowLayout

然后在您的swift文件中添加以下代码:-

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

       return CGSize(width: (self.view.frame.size.width - 60) / 2, height: (self.view.frame.size.width - 60) / 2)

   }