所以我试图将UICollectionView锚定到我的视图顶部。我用锚来帮助我。这是我到目前为止的代码:
var datePosted = new Date(post.publish_date).toString();
我使用这两段代码将MenuBar添加到ViewController中:
class MenuBar : UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let cellID : String = "menuCell"
lazy var collectionView : UICollectionView = {
let cv : UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
cv.backgroundColor = red
cv.translatesAutoresizingMaskIntoConstraints = false
//cv.isScrollEnabled = false
cv.delegate = self
cv.dataSource = self
return cv
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupCollectionView()
}
func setupCollectionView() {
addSubview(collectionView)
collectionView.register(MenuBarCell.self, forCellWithReuseIdentifier: cellID)
// setup menuBar constraints
collectionView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
collectionView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
collectionView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
collectionView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
cell.backgroundColor = .white
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
}
在let menuBar : MenuBar = {
let mb = MenuBar()
mb.translatesAutoresizingMaskIntoConstraints = false
return mb
}()
func setupMenuBar() {
view.addSubview(menuBar)
menuBar.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
menuBar.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
menuBar.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
menuBar.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
,我致电viewDidLoad
。
但是UICollectionView似乎总是被视图顶部的一定数量的像素所抵消,但我没有看到任何这种情况发生的原因。这就是我所看到的:
基本上我想要的是让最左边的单元格位于视图的左上角。
任何人都可以帮我解决这个问题吗?提前谢谢!