如何以编程方式为 ios、swift 3 中的集合视图单元格提供宽度和高度 [英] How to give width and height programatically for collection view cell in ios, swift 3
问题描述
我试图以编程方式为 collectionViewCell
提供高度和宽度.我使用了以下方法:
I tried to give the height and width for collectionViewCell
, programatically. I used following method:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let viewWidth = self.deviceWidth/3 - 5
let viewHeight = viewWidth
return CGSize(width :100,height: 100)
}
这没有用.甚至这种方法也没有显示为提示.帮我解决这个问题.在 Swift 3 中是否还有其他委托方法可以以编程方式设置单元格宽度和高度?
This didn't work. even this method didn't show as a hint. Help me with this. Is there any other delegate method to set the cell width and height programmatically in Swift 3?
推荐答案
Method collectionView(_:layout:sizeForItemAt:)
是 UICollectionViewDelegateFlowLayout
协议的方法,所以设置delegate
和datasource
的>collectionView
是不够的,您需要使用您添加了 collectionView
的自定义类来实现 UICollectionViewDelegateFlowLayout
来调用 UICollectionViewDelegateFlowLayout
协议的方法.所以实现 UICollectionViewDelegateFlowLayout
像下面的例子:
Method collectionView(_:layout:sizeForItemAt:)
is UICollectionViewDelegateFlowLayout
protocol's method, so setting delegate
and datasource
of collectionView
is not enough, you need to implement UICollectionViewDelegateFlowLayout
with your custom class where you have added collectionView
to call UICollectionViewDelegateFlowLayout
protocol's methods. So implement UICollectionViewDelegateFlowLayout
like below example:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
这篇关于如何以编程方式为 ios、swift 3 中的集合视图单元格提供宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!