2017-08-01 168 views
1

我有一个应用程序与屏幕分成四个相等的单元格。每个单元格都有一个图像,标签和颜色。我正在尝试添加图像,但由于某些原因,只有第一个单元格中的图像有效。在UICollectionView UIImageView没有正确绘制

现在看起来是这样的:enter image description here

这里是我的代码: 在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 
} 

标签和颜色做工精细,但由于某种原因,图像的观点似乎离开屏幕。我有一种感觉,我的中心/边界限制迫使图像离开屏幕,但我已经尝试了很多组合,并且它们都不适合我。

我该怎么做?

+1

如果您使用原型单元格会更好。你有没有试过看到View Hierarchy? –

+0

将一些其他图像放在pictureArray的开头,并检查该图像是否也绘制在第一个单元格中? – 3stud1ant3

+0

@YogeshSuthar我用图片和标题的IBOutlet创建了自己的UICollectionViewCell的子类,它工作正常!谢谢! –

回答

0

我发布了谁在谷歌这里的正确答案。 (而且因为它是一个小时就解决这个问题,没有任何人发布答案)

最好的做法是继承UICollectionViewCell,连接所有的网点(标签,图像等),并与这个类的细胞起作用

好运来所有

0

这是什么工作,约杰什Suthar的评论后:

我子类UICollectionViewCell,连接的图像和标签:

class NavigationCollectionViewCell: UICollectionViewCell { 
    @IBOutlet weak var navImage: UIImageView! 
    @IBOutlet weak var navLabel: UILabel! 
} 

然后,在ViewController中,我这样做:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! NavigationCollectionViewCell 


    // Set cell properties 
    cell.backgroundColor = colorArray[indexPath.row] 

    cell.navImage.image = imageArray[indexPath.row] 

    cell.navLabel.text = titleArray[indexPath.row] 

    return cell 
} 

坐落在Main.storyboard的图像和标签的大小和位置!