在Swift中将CollectionView作为子视图

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

ios - 在Swift中将CollectionView作为 subview-LMLPHP

这是我的代码:

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

    }
问题是“textView.frame”。 textview框架x和y点不为0

10-06 01:37