2 Replies
      Latest reply on Jan 9, 2019 10:20 PM by mksmurali
      mksmurali Level 1 Level 1 (0 points)

        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?

        • Re: How to replace an Image?
          Claude31 Level 8 Level 8 (5,565 points)

          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