简体   繁体   English

如何在Swift中使用UISlider更改UIImageView中的图像

[英]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. 我正在尝试使用UISlider来更改UIImageView中的图像所以我的想法是,如果滑块值为1,则某个图像显示它是否为2,不同的图像显示。 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. 我认为它应该是一个If / Else语句,但我不确定如何形成语法。

@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. 将滑块值转换为int。

  3. Use that int to index into the array of filenames. 使用该int索引文件名数组。

  4. Use image(named:) to load the image with that name. 使用image(named:)加载具有该名称的图像。

  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: 由于滑块具有Float值,并且您需要一个整数值来从数组中选择图像,我假设您要使用最接近的整数索引作为滑块的当前值:

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
   }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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