2015-10-03 72 views
3

我曾經假設將一個背景圖片添加到UICollectionViewCell很容易,但我很難找出它。我有一個像這樣的邊框圖像,我想將其添加到我的UICollectionView中的每個單元格中。如何在Swift中向UICollectionViewCell添加背景圖片?

border.png

enter image description here

我沒有看到一個選項,將其添加在Interface Builder和我不知道以編程方式上UICollectionViewCell使用的方法。

我看到這些類似的問題:

+0

我試着在IB中添加它,但沒有類似的方式來添加它,就像我會用UIButton一樣。 – Suragch

回答

1

添加一個UIImageView到您CollectionViewCell並將此形象作爲圖像。

3
let View=UIView() 
View.backgroundColor=UIColor(patternImage:UIImage(named:"border.png")!) 
cell.backgroundView=View 

uicollectionviewcellForItemAtIndexPath方法

+0

這不是使用IB – Abizern

+1

不使用IB也可以。我找不出任何方式,所以這種方式也有助於瞭解。 – Suragch

4

我知道這是一個老問題,與公認的答案。但爲什麼不只是像這樣設置單元格的邊框:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
{ 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) 

     cell.layer.borderWidth = 1.5 
     cell.layer.borderColor = UIColor.blueColor().CGColor 
     cell.layer.cornerRadius = 4 

    return cell 
} 

這樣你就不需要使用圖像。只需調整borderWidth和cornerRadius,直到獲得所需的效果。

+1

我覺得當我寫這個問題時,我還沒有學會如何在圖層上做邊框。我後來補充說,作爲[這個答案]的更新(http://stackoverflow.com/a/31735229/3681880)。所以是的,你的答案是對我原來的問題的更好的解決方案(+1)。但由於我的問題問如何添加背景圖片,我應該保留接受的答案。並非所有的背景圖片都必須是邊框。 – Suragch