0

I've UICollectionViewCell that is generated programmatically. There is label placed over cell.

Now, I want to set image to label present on cell but that image should resize according to size of cell.

Screenshot 1

Below is code used but it didn't worked :

 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)

Any other fix?

I tried using UIButton instead of UILabel as suggested by someone. But here another issues cropped-up like Alignment of text, Image is not set..

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

 . . .
Jayprakash Dubey
  • 35,723
  • 18
  • 170
  • 177

3 Answers3

1

Can you try setting content mode of the UIImageView after setting its frame? It can be done as follows

objImage.contentMode = UIViewContentMode.ScaleToFill

You can use ScaleToFill or ScaleAspectFill depending on your requirement. You can find more information about content modes here

Vishnu gondlekar
  • 3,896
  • 21
  • 35
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]
    }
Chirag Patel
  • 1,453
  • 1
  • 11
  • 21
1

set your button image view Content mode as ScaleAspectFit and at the same time set your button property setImage instead of setBackgroundImage?

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

for additional Help see this

Community
  • 1
  • 1
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143