CollectionView 作为 Swift 中的子视图

CollectionView as a Subview in Swift

CollectionView 作为 Swift

中的子视图

我尝试插入一个非常简单的 collectionView 作为子视图,但无法获得正确的框架。我究竟做错了什么?你能帮帮我吗?

这是我的代码:

import UIKit

class ViewController: UIViewController {

var collectionView: UICollectionView!

@IBOutlet weak var testView: UIView!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidLayoutSubviews() {

    setupCollectionView()

}

func setupCollectionView() {

    let layout = UICollectionViewFlowLayout()
    collectionView = UICollectionView(frame: testView.frame, collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor.green
    testView.addSubview(collectionView)

}

}

func setupCollectionView() {

    let layout = UICollectionViewFlowLayout()
    collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, testView.frame.size.width, height: testView.frame.size.height), collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor.green
    testView.addSubview(collectionView)
    testView.clipsToBounds=true

    }

问题是"testView.frame"。 testview 帧 x 和 y 点不为 0