使用未解决的标识符“视图”

时间:2018-09-11 18:09:07

标签: ios swift collectionview

试图向集合视图添加约束。 不断收到错误消息“使用未解决的标识符'view'” 非常感谢您的帮助。

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
    }

2 个答案:

答案 0 :(得分:1)

view中没有UIView属性,它是UIViewController的属性。

由于在这种情况下selfview,请替换:

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)
)]

答案 1 :(得分:0)

您需要用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