在Swift中将CollectionView作为子视图

Rom*_*man 1 frame subview ios uicollectionview swift

在Swift中将CollectionView作为子视图

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

在此处输入图片说明

这是我的代码:

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)

}
Run Code Online (Sandbox Code Playgroud)

}

Jay*_*iya 5

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

    }
Run Code Online (Sandbox Code Playgroud)

问题是“ testView.frame”。testview框架x和y点不为0