在Swift 4中心UICollectionViewCells
问题描述:
我正在使用UICollectionView,并且到目前为止我已经做得很好。我被困在UIViewLayout中,我想让单元居中。 我想让我的UICollectionView单元格中心。请看下面的图片。图1是我通过下面的代码实现的图像2是我想要的。请帮助家伙。 TIA 图片 - 1张 在Swift 4中心UICollectionViewCells
看看我的代码段。
import UIKit
class ViewController: UIViewController {
var collectionView: UICollectionView!
var sizingCell = StateCollectionViewCell()
var states = ["Alabama", "Alaska", "Arizona", "California",
"Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii",
"Idaho", "Indiana", "Lowas", "Kansas", "New Jersey", "Mexico",
"Missori", "Montana", "Newada", "New York", "Maine", "Maryland",
"Kentchuky"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a
nib.
setupCollectionView()
let layout = collectionView?.collectionViewLayout as!
UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: 100, left: 15, bottom: 10,
right: 20)
layout.estimatedItemSize = CGSize(width: 100, height: 100)
layout.itemSize = UICollectionViewFlowLayoutAutomaticSize
}
// Mark: - Initializing a collectionView and addint it to the VC's
current view
func setupCollectionView() {
let layout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: view.frame,
collectionViewLayout: layout)
collectionView.register(StateCollectionViewCell.self,
forCellWithReuseIdentifier: "stateCell")
collectionView.backgroundColor = UIColor.white
collectionView.delegate = self
collectionView.dataSource = self
view.addSubview(collectionView)
}
}
extension ViewController: UICollectionViewDelegate,
UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
//Mark: - Specifying the number of sections in the collectionView
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
//Mark: - Specifying the number of cells in given section
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return states.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "stateCell", for: indexPath)as! stateCollectionViewCell
cell.awakeFromNib()
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let stateCell = cell as! StateCollectionViewCell
stateCell.stateCell.text = states[indexPath.row]
}
}
答
我相信你可以做到这一点最简单的方法是继承UICollectionViewFlowLayout
并作出改变的属性,它不能的viewController内完成。因为我刚刚写了一个类似的自定义布局来做到这一点,使它成为一个吊舱,也许它(github link)可以提供帮助。
尝试此github [链接](https://github.com/keighl/KTCenterFlowLayout/blob/master/KTCenterFlowLayout.m) –
是的,我已经看到了这一点,但想要简单,就像我当前的代码中的更改。对于链接,您提供了我需要添加豆荚并进行许多更改。所以把它放在一边。 @AdityaSrivastava – iDeveloper
@iDeveloper仅仅因为一些UI界面看起来很简单,并不意味着实现它的过程很简单。简单可以用很多方式来定义,对于一些以前从未做过的人来说,对于某些专家来说很简单。然而,这是Aditya链接的自定义UICollectionViewFlowLayout的示例。 – 2017-09-03 08:20:19