【问题标题】:List of Images like InstagramInstagram 等图片列表
【发布时间】:2016-10-31 12:28:31
【问题描述】:

我想制作一个可滚动的图像列表,例如带有 4 列的 instagram。我创建了一个带有图像视图 http://prntscr.com/d15rnx 的集合视图。但我得到了这个结果 - http://prntscr.com/d15tsq 代码 -

// MARK: - UICollectionViewDataSource protocol

// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.items.count
}

// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    // Use the outlet in our custom class to get a reference to the UILabel in the cell
    cell.imageView.image = UIImage(named: "main/p\(self.items[indexPath.item].code)/main/main.jpg")
    print("main_card_images/p\(self.items[indexPath.item].code)/main/main")
    return cell
}

// MARK: - UICollectionViewDelegate protocol

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    print("You selected cell #\(indexPath.item)!")
    print(self.items[indexPath.item])
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let yourNextViewController = (segue.destination as! ViewControllerCard)
    let indexPath = collectionView.indexPath(for: sender as! UICollectionViewCell)
    yourNextViewController.mainCardImage = self.items[(indexPath?.item)!]
}

【问题讨论】:

  • 所以你想用很小的空间很好地缩小差距?

标签: ios swift xcode storyboard


【解决方案1】:

确保您已将单元间距设置为 0,然后您所要做的就是实现:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

      return(collectionView.bounds.size.width/4,collectionView.bounds.size.height/4)
}

这会将所有单元格的大小调整为等于UICollectionView 宽度的 1/4,从而在每行中创建 4 个单元格(高度值的 1/4 只是因为我喜欢这些类型的 UI 中的对称性)。如果单元格的数量似乎比这少,那是因为项目间的间距没有设置为 0。如果你想要项目间的间距,只需从上面函数中返回的宽度值中减去该值

或者

您可以实现自己的自定义流布局,但上述解决方案要简单得多。

【讨论】:

    【解决方案2】:

    我发现通过 Interface Builder 中的设置来配置我的集合视图是最简单的。对于具有流布局的集合视图,这里是我用于插图的设置。我发现项目尺寸宽度:125.8 和高度:125.8 为我提供了在大多数设备上以纵向或横向显示的最佳尺寸。

    这是我的收藏视图的样子。

    您当然可以使用UICollectionViewDelegateFlowLayout 以编程方式设置它,或者按照Rikh 的建议,通过子类化CollectionViewFlowLayout

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多