[英]How to fit the an image in to a collectionview?
我想在容器内插入一张图片。 但是当我运行这段代码时
//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! AppIconViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = self.items[indexPath.item]
cell.ImageView.image = UIImage.init(named: "page-01")
//cell.backgroundColor = UIColor.cyan
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
return cell
}
我的理解是图像大于框架导致框架扩展。
如何在内部设置图像以使其适合第一张图像中的框?
欢迎使用 Stackoverflow。
为此,您需要添加明确的高度和宽度约束。 我假设您在sizeForItemAt
方法中返回了合适的大小。
最后,不要忘记将cell
或ImageView
的clipsToBounds
为true
。
每行需要 3 个集合视图单元格,上面的图像将适合每个单元格。 您需要实现UICollectionViewDelegateFlowLayout委托方法来设置集合视图单元格。
我假设单元格是方形的,并且每个单元格和每行之间有 10px 的间隙(因此最小行间距和项目间距为 10)
let cellGap = 10
let leftGapToScreen = 10
let rightGapToScreen = 10
let minLineSpacing = 10
let minInterItemSpacing = 10
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let availableWidth = UIScreen.main.bounds.width - (2 * cellGap) -
leftGapToScreen - rightGapToScreen
let cellWidth = availableWidth / 3
let cellHeight = cellWidth
return CGSize(width: cellWidth, height: cellHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: leftGapToScreen, bottom: 0, right: rightGapToScreen)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return minLineSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return minInterItemSpacing
}
现在,创建一个自定义 collectionViewCell 并在其中放置一个 imageView。 使用自动布局,使图像完全适合超级视图。 希望它会有所帮助。
这是一个更简单的问题。 因此,将来我建议进行一些搜索,因为这样您将更快地学习基础知识。
cell.ImageView.image = UIImage.init(named: "page-01")
cell.ImageView.contentMode = .scaleAspectFill
cell.clipsToBounds = true
这是基本的纲要。 当您访问图像视图上的 .contentMode 属性时,您可能想尝试使用可用选项来查看您最喜欢哪个选项。
https://developer.apple.com/documentation/uikit/uiview/1622619-contentmode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.