【问题标题】:how to size cell in gridview如何在gridview中调整单元格的大小
【发布时间】:2017-07-09 04:31:43
【问题描述】:

我有一个像这样的网格列表

class ListViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{

private var collection: ACollection?
private var collectionViewLayout:UICollectionViewFlowLayout?


override func loadView() {
    super.loadView()

    collectionViewLayout = UICollectionViewFlowLayout()
    collectionViewLayout?.itemSize.width = 128
    collectionViewLayout?.itemSize.height = 227
    view = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewLayout!)
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let someObj: SomeObj = collection!.getObject(index: indexPath.item)
    let cell: UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(UICollectionViewCell.self), for: indexPath as IndexPath)
    let cellView: UIImageView = UIImageView(image: object.image)

    cellView.frame = cell.bounds
    cell.contentView.addSubview(cellView)
    return cell
}

我希望我的单元格具有不同的纵横比,尽管取决于 someObj 中的值。如何在不重叠的情况下调整单元格的大小?我试着做

cellView.frame = CGRect(x:0,y:0,width:100,height:300)
cellView.frame =cell.bounds

但单元格重叠。

【问题讨论】:

  • 我认为你应该在UICollectionViewDelegateFlowLayout 中实现collectionView(, layout: sizeForItemAt:) 函数,因为看起来你正在使用流布局。
  • @sCha 有点用。我看到的是,当我更改大小时,它会使用旧尺寸绘制一个单元格,然后在顶部绘制一个新尺寸的单元格

标签: iphone swift layout autolayout


【解决方案1】:

也许我会详细说明这个问题。

首先,如果你实现collectionView(_:layout:sizeForItemAt:)方法,你不需要指定以下内容:

collectionViewLayout?.itemSize.width = 128
collectionViewLayout?.itemSize.height = 227

这是每个单元格的默认大小。

其次,您在每个默认单元格顶部看到的重叠可能是您在重用单元格上添加的cellViews (UIImageViews)。问题是,每次委托请求单元格时,您都试图在当前单元格上添加UIImageView。您需要检查UIImageView 是否已经存在,因为整个单元格可能已被重用,但仍保留先前添加的图像视图。

【讨论】:

  • @user2175783 要么向视图添加标签并使用viewWithTag 方法引用它,要么您可以定义自定义单元格并使用它,以便它带有您需要的所有子视图。我个人推荐第二种选择,但第一种选择更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
  • 2013-05-26
  • 1970-01-01
相关资源
最近更新 更多