如何在 swift 中将 xib 的视图连接到另一个视图控制器的视图?

问题描述 投票:0回答:1

我有一个关于视图的问题。
如何让mainVC xib的视图连接menuVC的视图?
为什么我设置了这个代码却不能显示背景颜色?

self.cvBottom = menuView

或者我错过了一些设置?
或者我只是在编程中只使用自动布局?
谢谢。

class MainVC: UIViewController {
    
    @IBOutlet weak var cvBottom: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupView()
    }

    func setupView() {

        self.setupBottomCollectionView()
    }

    func setupBottomCollectionView() {
        
        let menuView = MenuController(collectionViewLayout: UICollectionViewFlowLayout()).collectionView
        self.cvBottom = menuView //Not work here. What's wrong?
    }
    
}


class MenuController: UICollectionViewController {
    
    fileprivate let cellId = "MenuCell"
    
    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.backgroundColor = .red
        collectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellId)
    }

}

extension FavoriteMenuController {
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MenuCell
        cell.lbTitle.text = "\(indexPath.row)"
        cell.backgroundColor = .darkGray
        return cell
    }
    
}

ios swift view autolayout
1个回答
0
投票

首先,一般来说,“替换”一个

@IBOutlet
是个坏主意。

其次,您正在从

view
中“提取”
MenuController
但您没有加载它的任何 code ...您需要将其添加为 child 视图控制器。

因此,在

MainVC
中,将您的
cvBottom
集合视图替换为普通的
UIView
。然后我们将从
MenuVC
添加视图作为子视图:

class MainVC: UIViewController {
    
    @IBOutlet weak var cvBottom: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupView()
    }
    
    func setupView() {
        
        self.setupBottomCollectionView()
    }
    
    func setupBottomCollectionView() {
        
//      let menuView = MenuController(collectionViewLayout: UICollectionViewFlowLayout()).collectionView
//      self.cvBottom = menuView //Not work here. What's wrong?

        // load menuView CONTROLLER
        let menuView = MenuController(collectionViewLayout: UICollectionViewFlowLayout())
        
        // add it as a child view controller
        addChild(menuView)
        
        // add menuView's view as a subview of cvBottom
        self.cvBottom.addSubview(menuView.view)
        
        // set its frame and resizing mask
        menuView.view.frame = self.cvBottom.bounds
        menuView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        // finish the "add child" process
        menuView.didMove(toParent: self)

    }
    
}
© www.soinside.com 2019 - 2024. All rights reserved.