简体   繁体   中英

How to change image in UIImageView with UISlider in Swift

I'm trying to use the UISlider to change images in UIImageView So the idea is that if the slider value is 1, a certain image shows if it's 2, different image shows. etc.

Can someone please help?

Edit: This is the code I tried. I think it's supposed to be an If/Else statement but I'm not sure how to form the syntax.

@IBOutlet weak var scaleLabel: UILabel!
@IBOutlet weak var scaleSlider: UISlider!
@IBOutlet weak var scaleImage: UIImageView!



@IBAction func valueChanged1(sender: AnyObject) {

    if scaleSlider.value == 1 {
        scaleImage.image = "Image.png"
    }

}
  1. Create an array of filenames.

  2. Convert your slider value to an int.

  3. Use that int to index into the array of filenames.

  4. Use image(named:) to load the image with that name.

  5. Install the image into your image view.

See if you can convert those steps to code. If not edit your question to show your code and tell us what happens and we'll show you how to debug it.

Since slider has a Float value and you need an integer value to pick image from array, I assume that you want to use the closest integer index for current value of the slider:

let images = [
    UIImage(named: "image1"),
    UIImage(named: "image2"),
    UIImage(named: "image3")
]

var currentIndex = 0 {
    didSet {
        if oldValue != currentIndex {
            currentIndexUpdated()
        }
    }
}

@IBAction func valueChanged(_ sender: UISlider) {
    currentIndex = Int(round(sender.value))
}

func currentIndexUpdated() {
    guard 0..<images.count ~= currentIndex else { return }
    imageView.image = images[currentIndex]
}

do like

@IBAction func valueChanged1(_ sender: UISlider) {

 var imageName : String = "Image.png"

 switch (sender.value)
{
  case 0:
    print("zero")
  imageName = "yyyy.png"

  case 1:
    print("one")
  imageName = "zzzz.png"
  case 2:
    print("two")
   imageName = "aaaa.png"

  default:
    print("Integer out of range")
 }

  if let image = UIImage(named:imageName) {
    scaleImage.image = image
   }

}

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