How to replace an Image?

Hi,

On clicking on a button in viewcontrollerA,it should navigate to viewcontrollerB and viewcontrollerB should have 4 Imageviews containing uinque, random images from an Image array.Image array has 10 images.

How to implement this?

Accepted Reply

You have a few things to do at least :


- go to the second view controller through a segue

=> perform segue in the button action or directly connect the button to ViewController B in IB


- create an array containing the references (names) of 10 images that you have put in your app's resources

let imageNames = ["image0", "image1" … ]


- in viewDidload of the VC B, pick 4 random (different) numbers from the 10

The simplest way is:

let sequence = 0 ..< 10
let shuffledSequence = sequence.shuffled()     // You put the sequence in random order
let selection = shuffledSequence[0...3]        // You pick the first 4 items


- load the 4 UIImageViews you have defined in VC B with the UIImages associted to those numbers.

Use collection of IBOutlets to make it easier to code


@IBOutlet var imageViews: [UIImageView]! // Connect each image in IB to this collection of IBOutlets, in the correct order


in viewDidLoad


let sequence = 0 ..< 10
let shuffledSequence = sequence.shuffled()     // You put the sequence in random order
let selection = shuffledSequence[0...3]        // You pick the first 4 items
for i in selection {
     imageViews[i].image = UIImage(named: imageNames[selection[i]])
}



Note: your post should better be in Getting Started or Cocoa Touch section, it is not really a Swift question

Replies

You have a few things to do at least :


- go to the second view controller through a segue

=> perform segue in the button action or directly connect the button to ViewController B in IB


- create an array containing the references (names) of 10 images that you have put in your app's resources

let imageNames = ["image0", "image1" … ]


- in viewDidload of the VC B, pick 4 random (different) numbers from the 10

The simplest way is:

let sequence = 0 ..< 10
let shuffledSequence = sequence.shuffled()     // You put the sequence in random order
let selection = shuffledSequence[0...3]        // You pick the first 4 items


- load the 4 UIImageViews you have defined in VC B with the UIImages associted to those numbers.

Use collection of IBOutlets to make it easier to code


@IBOutlet var imageViews: [UIImageView]! // Connect each image in IB to this collection of IBOutlets, in the correct order


in viewDidLoad


let sequence = 0 ..< 10
let shuffledSequence = sequence.shuffled()     // You put the sequence in random order
let selection = shuffledSequence[0...3]        // You pick the first 4 items
for i in selection {
     imageViews[i].image = UIImage(named: imageNames[selection[i]])
}



Note: your post should better be in Getting Started or Cocoa Touch section, it is not really a Swift question

Hi Claude31,

Thank you very much...