[ios] Programmatically set image to UIImageView with Xcode 6.1/Swift

I'm trying to set UIImageView programmatically in Xcode 6.1:

@IBOutlet weak var bgImage: UIImageView!

var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(bgImage)

But Xcode is saying "expected declaration" with bgImage = UIImageView(image: image) Image "afternoon"is a PNG, and my understanding is PNG does not need an extension in XCode 6.1.

Also tried just bgImage.image = UIImage(named: "afternoon"), but still get:

enter image description here

UPDATE

OK, I have put the code to update UIImageView into the viewDidLoad function, but UIImageView is still not showing the image (which exists in the base directory as afternoon.png):

@IBOutlet weak var bgImage: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    updateTime()
    var timer = NSTimer()
    let aSelector : Selector = "updateTime"
    timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)

    var image : UIImage = UIImage(named:"afternoon")!
    bgImage = UIImageView(image: image)
}

This question is related to ios xcode swift

The answer is


This code is in the wrong place:

var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(bgImage)

You must place it inside a function. I recommend moving it inside the viewDidLoad function.

In general, the only code you can add within the class that's not inside of a function are variable declarations like:

@IBOutlet weak var bgImage: UIImageView!

In Swift 4, if the image is returned as nil.

Click on image, on the right hand side (Utilities) -> Check Target Membership


With swift syntax this worked for me :

    let leftImageView = UIImageView()
    leftImageView.image = UIImage(named: "email")

    let leftView = UIView()
    leftView.addSubview(leftImageView)

    leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
    leftImageView.frame = CGRect(x: 10, y: 10, width: 20, height: 20)
    userNameTextField.leftViewMode = .always
    userNameTextField.leftView = leftView

You just need to drag and drop an ImageView, create the outlet action, link it, and provide an image (Xcode is going to look in your assets folder for the name you provided (here: "toronto"))

In yourProject/ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imgView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        imgView.image = UIImage(named: "toronto")
    }
}

If you want to do it the way you showed in your question, this is a way to do it inline

class YourClass: UIViewController{

  @IBOutlet weak var tableView: UITableView!
  //other IBOutlets

  //THIS is how you declare a UIImageView inline
  let placeholderImage : UIImageView = {
        let placeholderImage = UIImageView(image: UIImage(named: "nophoto"))
        placeholderImage.contentMode = .scaleAspectFill
        return placeholderImage
    }()

   var someVariable: String!
   var someOtherVariable: Int!

   func someMethod(){
      //method code
   }

   //and so on
}

How about this;

myImageView.image=UIImage(named: "image_1")

where image_1 is within the assets folder as image_1.png.

This worked for me since i'm using a switch case to display an image slide.


OK, got it working with this (creating the UIImageView programmatically):

var imageViewObject :UIImageView

imageViewObject = UIImageView(frame:CGRectMake(0, 0, 600, 600))

imageViewObject.image = UIImage(named:"afternoon")

self.view.addSubview(imageViewObject)

self.view.sendSubviewToBack(imageViewObject)

In xcode 8 you can directly choose image from the selection window (NEW)...

  • You just need to type - "image" and you will get a suggestion box then select -"Image Literal" from list (see in attached picture) and

  • then tap on the square you will be able to see all images(see in
    second attached picture) which are in your image assets... or select other image from there.

enter image description here

  • Now tap on square box - (You will see that square box after selecting above option)

enter image description here


Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to xcode

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64 iPhone is not available. Please reconnect the device Make a VStack fill the width of the screen in SwiftUI error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1 Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Xcode 10: A valid provisioning profile for this executable was not found Xcode 10, Command CodeSign failed with a nonzero exit code

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?