Swift - Using value from UISlider IBAction in another function

846 views Asked by At

This is a super basic question that is troubling me.

I have a UIslider IBAction that is generating a Double (var = rounded). I want to use this double in viewDidLoad. but getting the error "Use of unresolved identifier 'rounded'"

@IBAction func sliderValueChanged(sender: UISlider) {
    var currentValue = Double(sender.value)
    var rounded = Double(round(100*currentValue)/100)
    label.text = "\(rounded)"
}


override func viewDidLoad() {
    super.viewDidLoad()
    let fileURL = NSBundle.mainBundle().URLForResource("puppy", withExtension: "jpg")
    let beginImage = CIImage(contentsOfURL: fileURL)
    let filter = CIFilter(name: "CISepiaTone")
    filter.setValue(beginImage, forKey: kCIInputImageKey)
    filter.setValue(rounded, forKey: kCIInputIntensityKey)
    let newImage = UIImage(CIImage: filter.outputImage)
    self.imageView.image = newImage
}

filter.setValue(rounded, forKey: kCIInputIntensityKey) is where i am getting the error. I want to use the 'rounded' variable from the slider function here.

Any help in using one variable from one function in another function would be very much appreciated. I have ran into this a couple times without success. So once you all help me out here, it should fix my other issues as well.

Thanks

2

There are 2 answers

3
vadian On
  1. Declare an instance variable at the beginning of the class – outside any method – with the default value of the UISlider

    var rounded : Double = <defaultValueOfTheSlider>
    
  2. delete the keyword var before rounded in sliderValueChanged()

0
some_id On

A few concepts that will help you out. The issue you are having is that you are creating an instance inside a function and it is lost when the function returns. The reason for this is that the functions data is created on the stack, the stack is temporary memory your app's process uses.

To access the variable throughout the class you can declare it at the top of your class. This will then be allocated to the heap so that it's available for later access until removed from the heap(deallocated).