OGeek|极客世界-中国程序员成长平台

标题: ios - Instagram 等图片列表 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:58
标题: ios - Instagram 等图片列表

我想制作一个可滚动的图像列表,例如带有 4 列的 instagram。我创建了一个带有 ImageView 的 Collection View 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)!]
}



Best Answer-推荐答案


确保您已将单元间距设置为 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 只是因为我喜欢这些类型的对称性用户界面)。如果单元格的数量似乎比这少,那是因为项目间的间距没有设置为 0。如果你想要项目间的间距,只需从上面函数中返回的宽度值中减去该值

或者

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

关于ios - Instagram 等图片列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40342212/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4