繁体   English   中英

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

[英]Use of unresolved identifier 'view'

试图向集合视图添加约束。 不断收到错误消息“使用未解决的标识符'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
    }

UIView没有view属性,它是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)
)]

您需要用self替换view,因为这不是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM