尝试向集合视图添加约束。继续收到错误,“使用未解析的标识符'视图'”非常感谢任何帮助。
import UIKit
class MenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
// cv.backgroundColor = UIColor.white
cv.dataSource = self
cv.delegate = self
return cv
}()
let cellId = "cellId"
override init(frame:CGRect) {
super.init(frame: frame)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
addSubview(self.collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.leadingAnchor.constraint(
equalTo: view.leadingAnchor).isActive = true
collectionView.trailingAnchor.constraint(
equalTo: view.trailingAnchor).isActive = true
collectionView.topAnchor.constraint(
equalTo: view.topAnchor,
constant: -20).isActive = true
collectionView.heightAnchor.constraint(
equalTo: view.heightAnchor,
multiplier: 0.10).isActive = true
backgroundColor = UIColor.red
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.backgroundColor = .blue
return cell
}
在view
没有UIView
财产,它是UIViewController
的财产。
由于在这种情况下self
是view
,请替换:
equalTo: view.leadingAnchor).isActive = true
有:
equalTo: self.leadingAnchor).isActive = true
和其他人一样。
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: self.topAnchor,constant: -20),
collectionView.heightAnchor.constraint(equalTo: self.heightAnchor,multiplier: 0.10)
)]
你需要用self
替换视图,因为这不是viewcontroller这是MenuView所以你需要使用self for that
:
collectionView.leadingAnchor.constraint(
equalTo: self.leadingAnchor).isActive = true
collectionView.trailingAnchor.constraint(
equalTo: self.trailingAnchor).isActive = true
collectionView.topAnchor.constraint(
equalTo: self.topAnchor,
constant: -20).isActive = true
collectionView.heightAnchor.constraint(
equalTo: self.heightAnchor,
multiplier: 0.10).isActive = true