我对collectionView有一些奇怪的问题。
首先,我有一个UIView子类,里面有collectionView。看起来像这样
class UsersListMenu:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
lazy var collectionView:UICollectionView = {
var layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
var collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
let cellId = "cellId"
let menuArrayItems = ["Подходящие", "Онлайн", "Новые", "Рядом", "Избранные"]
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(collectionView)
collectionView.leadingAnchor.constraintEqualToAnchor(leadingAnchor).active = true
collectionView.trailingAnchor.constraintEqualToAnchor(trailingAnchor).active = true
collectionView.topAnchor.constraintEqualToAnchor(topAnchor).active = true
collectionView.bottomAnchor.constraintEqualToAnchor(bottomAnchor).active = true
collectionView.registerClass(UsersListMenuCell.self, forCellWithReuseIdentifier: cellId)
collectionView.backgroundColor = .whiteColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! UsersListMenuCell
cell.label.text = menuArrayItems[indexPath.item]
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(100, 40)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsZero
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
}
如您所见,单元格高度设置为40.然后我在ViewController中创建该视图的实例
class UsersListViewController: UIViewController {
var menu:UsersListMenu = {
var menu = UsersListMenu()
menu.translatesAutoresizingMaskIntoConstraints = false
return menu
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(menu)
menu.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 80).active = true
menu.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
menu.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
menu.heightAnchor.constraintEqualToConstant(40).active = true
}
}
菜单看起来空白的问题 - 细胞无法看到
除非我将视图控制器中的菜单高度设置为100
menu.heightAnchor.constraintEqualToConstant(100).active = true
然后看起来像这样
这里发生了什么?