我有一个应用程序与屏幕分成四个相等的单元格。每个单元格都有一个图像,标签和颜色。我正在尝试添加图像,但由于某些原因,只有第一个单元格中的图像有效。在UICollectionView UIImageView没有正确绘制
这里是我的代码: 在ViewController.swift:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
colorArray += [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
pictureArray += [UIImage(named: "budget")!, UIImage(named: "journey")!,
UIImage(named: "learn")!, UIImage(named: "settings")!]
titleArray += ["Budget", "Journey", "Learn", "Settings"]
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as UICollectionViewCell
// Set cell properties
cell.backgroundColor = colorArray[indexPath.row]
let imageview:UIImageView=UIImageView(image: pictureArray[indexPath.row])
let size = CGSize(width: 100, height: 100)
imageview.center = cell.center
imageview.bounds = CGRect(origin: cell.bounds.origin, size: size)
cell.contentView.addSubview(imageview)
let label = cell.viewWithTag(1) as! UILabel
label.text = titleArray[indexPath.row]
return cell
}
标签和颜色做工精细,但由于某种原因,图像的观点似乎离开屏幕。我有一种感觉,我的中心/边界限制迫使图像离开屏幕,但我已经尝试了很多组合,并且它们都不适合我。
我该怎么做?
如果您使用原型单元格会更好。你有没有试过看到View Hierarchy? –
将一些其他图像放在pictureArray的开头,并检查该图像是否也绘制在第一个单元格中? – 3stud1ant3
@YogeshSuthar我用图片和标题的IBOutlet创建了自己的UICollectionViewCell的子类,它工作正常!谢谢! –