gpt4 book ai didi

ios - Swift:让 UICollectionView 动态改变它的大小

转载 作者:行者123 更新时间:2023-11-28 08:11:36 25 4
gpt4 key购买 nike

目标:我有一个默认有 7 列和 6 行单元格的 UICollectionView。现在用户应该能够通过 UIStepper 更改列和行的数量。像这样:

var numberOfColumns: Int = 7

@IBAction func changeNumberOfColumns(_ sender: UIStepper) {
numberOfColumns = Int(sender.value)
boardSizingCollectionView.reloadData()
}

extension BoardSizingViewController: UICollectionViewDataSource {

func numberOfSections(in collectionView: UICollectionView) -> Int {
return numberOfRows
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfColumns
}

func collectionView(_ collectionsiView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Field", for: indexPath) as! FieldCollectionViewCell
cell.tokenView.backgroundColor = .white
cell.tokenView.layer.cornerRadius = (cell.frame.width - 8 * 2) / 2
return cell
}
}

单元格应保持其大小,而不是调整 UICollectionView 的大小。

问题:我无法在代码中直接设置 UICollectionView 的宽度和高度,因为这些是只获取属性。另外,如果我使用

boardSizingCollectionView.frame.size = CGSize(width: FieldCollectionViewCell.frame.width * numberOfColumns, height: FieldCollectionViewCell.frame.height * numberOfRows)

我得到一个错误,因为我的 FieldCollectionViewCell 是一个 CGRect,我不知道如何准确访问 CGRect 的大小。

肉体中的另一个钩子(Hook)是,myCollectionView 对其 x 和 y 位置有限制,以便在不同设备上自动定位,因此 myCollectionView 必须至少在 viewDidLoad() 中获得宽度和高度。

对我有什么提示吗?非常感谢转发!

最佳答案

您不能直接修改框架。但是,您可以为问题分配一个新框架。

I can't directly set the width and height of a UICollectionView in code, because these are get-only properties. Also if I use

    //get the current frame
var collectionViewFrame = self.collectionView.frame
//set the size
collectionViewFrame.size = CGSize(width: FieldCollectionViewCell.frame.width * numberOfColumns, height: FieldCollectionViewCell.frame.height * numberOfRows)
//again set the frame
self.collectionView.frame = collectionViewFrame

关于ios - Swift:让 UICollectionView 动态改变它的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43608101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com