let numberOfCellsPerRow: CGFloat = 3
override func viewDidLoad() {
super.viewDidLoad()
layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height), collectionViewLayout: layout)
collectionView.backgroundColor = .clear
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = (view.frame.width - max(0, numberOfCellsPerRow - 1) * layout.minimumInteritemSpacing) / numberOfCellsPerRow
return CGSize(width: cellWidth, height: 75.0)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let itemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
itemCell.backgroundColor = .black
return itemCell
}
垂直方向
水平方向
我希望所有单元格都在同一行。为什么第一个单元格的左侧有一些边距(水平方向)?如果我以水平方向启动应用程序,则在垂直方向的单元格之间会出现一些空间。
答案 0 :(得分:0)
您可以尝试使用自动布局
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
])
或刷新viewWillTransition
内的框架
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.collectionView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
self.collectionView.collectionViewLayout.invalidateLayout()
}