简体   繁体   中英

Swift: Adding UIImage?

How do I add an image via Swift with the UIImage command? This is my current code:

var imageView = UIImageView(frame: CGRectMake(100, 100, 150, 150));     
myPic = UIImage(named: "bowling");
imageView.image = myPic;
self.view.addSubview(imageView);

It does not show anything, and this is under viewDidLoad() , which should load by default.

Thanks! :)

It's better to put the image view on your view controller in IB (Interface Builder), connect an outlet, and then install an image into it in code.

Getting the image to appear in the correct place and at the right size requires different steps depending on whether you're using AutoLayout or AutoResizingMasks (aka old style "struts-and-springs" layout.)

If you're using AutoLayout, which is the default, you need to add constraints that give your view a size and a location in it's view. At a minimum you should set the view's height and width and set it's vertical and horizontal center relative to it's superview's center. (Note that you have to add it to its superview before adding constraints.)

Adding constraints is easier in IB than in code.

Your second line should read let myPic = UIImage(named: "bowling"); , since you have not defined myPic yet, but it's much easier to add an image view in the storyboard, connect an outlet to the view controller code, then define what image the view should contain.

silver_belt answered this for me. Silly me, I never added the picture to the project hierarchy! Thanks a million guys! :)

"Can you confirm that you have an image named "bowling" in an Asset Catalog or added as a resource to your project? I know it might sound silly... but also keep in mind filenames are case-sensitive on devices (not in the simulator)."

Make sure your "bowling" image is added to your project (as a resource, or in an Asset Catalog).

Keep in mind filenames on devices are case-sensitive, while the simulator is not.

Your UIImage and UIImageView code is otherwise fine.

Try this:-

    var imageViewBowline: UIImageView = UIImageView()
    imageViewBowline.frame = CGRectMake(100, 100, 150, 150)
    var myPicture = UIImage(named: "bowling.jpg")
    imageViewBowline.image = myPicture 
    self.view.addSubview (imageViewBowline)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM