这就是我所拥有的:
具有2列的集合视图,每列具有相等的距离。
每个单元格都加载SmallCardView.xib。 SmallCardView包含一个方形图像,下面有一些文字。
问题:
我希望视图的宽度与其父级(单元格)的宽度相匹配。通过比较屏幕尺寸可以最好地说明这一点
如上所示,单元格(紫色轮廓)在两个屏幕上都正确调整,但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)
}
}
谢谢!
您可以将具有约束的视图嵌入到边:
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)
首先从故事板中获取collectionview。设置它的约束如下: -
然后选择collectionview并删除默认为10的行填充。因此,更新为20.因此,cellfeding每边应为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)
}