2016-08-12 156 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 –