ios - CollectionView 作为 Swift 中的 subview

标签 ios swift uicollectionview frame subview

CollectionView 作为 Swift 中的 subview

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

enter image description here

这是我的代码:

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

关于ios - CollectionView 作为 Swift 中的 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43086669/

相关文章:

ios - 如何避免此 SwiftUI + Combine Timer Publisher 引用周期/内存泄漏?

ios - 离开屏幕时表格单元格的行为极其奇怪

objective-c - 如何将 MIDI 消息编程为 HUI Pro Tools 使用?

ios - 在 swift2 中,是否可以将具有 2 个元素的元组分配给 2 个变量,其中一个是常量,一个可以改变

swift - 在 swift 中调用 viewWillAppear 方法时,我的 textFields 不会消失

ios - 如何获取 Objective C 中特定类的所有已分配实例?

swift - TableViewController 中的多个自定义单元格

ios - 动画后 UICollectionViewCell 位置错误

swift - 从 UICollectionViewCell 中点击按钮时如何引用 UITableViewCell?

ios - UILabel隐藏文本问题