5

I'm just trying to create a UIImage View programmatically, I have a new view and I tried doing this

let imageName = "yourImage.png"
view.backgroundColor = UIColor.colorWithPatternImage(UIImage(named:imageName))

This code doesn't work. please help me as soon as possible

nhgrif
  • 61,578
  • 25
  • 134
  • 173
Laxman Ghimire
  • 87
  • 1
  • 1
  • 7
  • 1
    possible duplicate of [How do you create a UIImage View Programmatically - Swift](http://stackoverflow.com/questions/26569371/how-do-you-create-a-uiimage-view-programmatically-swift) – Burhanuddin Sunelwala Apr 05 '15 at 09:16
  • Hi, we **want** to help you, but with "*This code doesn't work*" we don't have enough information. **How** does it not work? **What** happens? Also, writing "*please help me as soon as possible*" won't elicit answers any sooner... – Wai Ha Lee Apr 05 '15 at 09:16

2 Answers2

14

This is for image with 100 height and 100 width:

var imageViewObject :UIImageView
imageViewObject = UIImageView(frame:CGRectMake(0, 0, 100, 100));
imageViewObject.image = UIImage(named:"imageName.png")
self.view.addSubview(imageViewObject)

To resize the image to fit the view frame:

    imageViewObject.contentMode = UIViewContentMode.ScaleToFill
 or
    imageViewObject.contentMode = UIViewContentMode.ScaleAspectFit
or
    imageViewObject.contentMode = UIViewContentMode.ScaleAspectFill 
Want Query
  • 1,396
  • 1
  • 11
  • 12
4

First create UIImageView , add image in UIImageView with frame and than give image Name.The following code help you.

var imageView : UIImageView
imageView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
imageView.image = UIImage(named:"image.jpg")
self.view.addSubview(imageView)
Bhuwan Sharma
  • 269
  • 1
  • 2
  • 11