【发布时间】:2021-07-31 11:53:19
【问题描述】:
我在使用自定义 UICollectionViewCell 时遇到问题。自定义单元格有一个 UILabel 和一个 UIImageView。问题是,当我将图像放在 UIImageView(左截图)上时,同一单元格中的 UILabel 会消失,如下图所示。但是如果 UIImageView 上没有 Image 源,则 UILabel 不会丢失。
这是具有 UICollectionView 的 Viewcontroller 的代码
class CatTowerVeiwController: UIViewController {
@IBOutlet weak var popCountSwitch: UISwitch!
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let switchState = UserDefaults.standard.bool(forKey: UserDataKey.popCountVisibility)
popCountSwitch.setOn(switchState, animated: false)
collectionView.register(UINib(nibName: "CatTowerCell", bundle: nil), forCellWithReuseIdentifier: "cell")
setupFlowLayout(numberOfCells: 2.0)
}
@IBAction func doneButtonClicked(_ sender: UIButton) {
let isLabelVisible = self.popCountSwitch.isOn
UserDefaults.standard.set(isLabelVisible, forKey: UserDataKey.popCountVisibility)
self.dismiss(animated: false)
}
}
extension CatTowerVeiwController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CatTowerCell
// cell.cellImage.image = #imageLiteral(resourceName: "popcat_closed")
cell.cellName.text = "Popcat"
print(cell.cellName.frame.size.height)
print(cell.cellName.frame.size.width)
return cell
}
}
extension CatTowerVeiwController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let leftAndRightPaddings: CGFloat = 45.0
let numberOfItemsPerRow: CGFloat = 2.0
let width = (collectionView.frame.width-leftAndRightPaddings)/numberOfItemsPerRow
return CGSize(width: width, height: width)
}
private func setupFlowLayout(numberOfCells: CGFloat) {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
let halfWidth = UIScreen.main.bounds.width / numberOfCells
flowLayout.itemSize = CGSize(width: halfWidth * 0.8 , height: halfWidth * 0.8)
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = halfWidth * 0.1
self.collectionView.collectionViewLayout = flowLayout
}
}
这是自定义单元格的代码
class CatTowerCell: UICollectionViewCell {
@IBOutlet weak var cellImage: UIImageView!
@IBOutlet weak var cellName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
这就是我想要做的:
【问题讨论】:
-
你对图像和标签有什么限制?您是否设置了他们的内容拥抱/抗压优先级?
-
请检查您是否使用了正确的图片名称,该图片是否在图片资源中可用?
-
更改出现顺序,标签在最前面。
-
@Sweeper 说这是约束问题。检查您的约束或简单地分配 imageview 背景颜色并检查。你会明白的。
-
@JarvisTheAvenger 我检查了图片名称是否正确
标签: ios swift uicollectionview uikit uicollectionviewcell