2016-08-12 112 views
0

我已經編程生成了UICollectionViewCell。在單元格上放置了標籤。Swift:如何將圖像設置爲符合標籤尺寸的標籤?

現在,我想設置圖像標籤目前在單元格上,但該圖像應根據單元格的大小調整大小。

Screenshot 1

下面是使用代碼,但它沒有工作:

let objImage : UIImage = UIImage(named: "OK")! 
let objCGSize = cell.lblNumber?.frame.size 

UIGraphicsBeginImageContext(objCGSize!) 
objImage.drawInRect(CGRectMake(0, 0, (cell.lblNumber?.frame.size.width)!, (cell.lblNumber?.frame.size.height)!)) 

let objNewImage : UIImage = UIGraphicsGetImageFromCurrentImageContext() 
      UIGraphicsEndImageContext() 

cell.lblNumber!.text = "" 
cell.lblNumber!.backgroundColor = UIColor(patternImage: objNewImage) 

任何其他解決?

我嘗試使用UIButton而不是UILabel,如某人所建議的。但這裏的另一個問題隨之而來,像文本的對齊方式,圖像沒有設置..

Screenshot 2

. . . //Code for UIButton instead of UILabel 

cell.btnNumber.setTitle("", forState: .Normal) 
    //cell.btnNumber.setImage(UIImage(named: "OK"), forState: .Normal) 
cell.btnNumber.imageView?.image = UIImage(named: "OK") 
cell.btnNumber.imageView?.contentMode = UIViewContentMode.ScaleAspectFit 

. . . 
+0

就是這個按鈕或標籤兄弟 –

+0

@ Anbu.Karthik:標籤上你爲什麼不選用了imageview的或這一概念的按鈕CollectionViewCell –

+0

的頂部,這是非常易於工作 –

回答

1
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCellWithReuseIdentifier("hobbiesCell", forIndexPath: indexPath) as! HobbiesTagCell 
     self.configureCell(cell, forIndexPath: indexPath) 
     return cell 
    } 

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
     self.configureCell(self.sizingCell!, forIndexPath: indexPath) 
     return self.sizingCell!.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) 
    } 
func configureCell(cell: HobbiesTagCell, forIndexPath indexPath: NSIndexPath) { 
     let tag = tags[indexPath.row] 
     cell.hobbiesTagName.text = yourArrname[indexPath.item] 
    } 
1

你可以嘗試設置它的框架後設置的UIImageView的內容模式?它可以如下

objImage.contentMode = UIViewContentMode.ScaleToFill 

您可以使用ScaleToFillScaleAspectFill根據您的要求來完成。您可以找到有關內容模式here

+0

這沒有奏效! –

1

設置您的按鈕圖像視圖內容模式ScaleAspectFit,並在同一時間的詳細信息設置你的按鈕屬性setImage代替setBackgroundImage

yourbutton.imageView?.contentMode =.ScaleAspectFit 
yourbutton.contentHorizontalAlignment = .Fill 
yourbutton.contentVerticalAlignment = .Fill 
yourbutton.setImage(UIImage(named: stretchImage)!, forState: .Normal) 

額外的幫助看this

+0

問題已編輯。覈實。除了圖片之外,一個新的問題也被加劇了。文本的排列位於單元格的右下角。 –

+0

文字也按鈕或一個labelbro –

+0

@JayprakashDubey - 檢查更新的答案bro –