2017-08-01 78 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的圖像和標籤的大小和位置!