DanB DanB - 2 months ago 8
iOS Question

Swift 2 - Print New Value from Slider at Regular Interval

I am trying to print a value from a slider at regular intervals. But only print the value if it is different to that last printed. I also do not want to miss any of the output values from the slider.

To do this I have created an array and added an element to the start of that array if it is different to the one already at the start. I have then used a repeating NSTimer to regularly call a function that prints the last element in the array before removing it from the array.

What happens when I run the app is the NSTimer stops anything being printed for it's set time, but then all of the elements print at once and more than one of each print. I've tried messing about with lots of different things - this is the closest I have got to making it work.

If you need to know any more info let me know.

I really appreciate any help given, thanks very much.

var sliderArray: [Float] = []
var timer: NSTimer!
let step: Float = 1

@IBAction func sliderValueChanged(sender: AnyObject)
{
let roundedValue = round(slider.value / step) * step
slider.value = roundedValue

if sliderArray.first != slider.value
{
sliderArray.insert(slider.value, atIndex: 0)
}

NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(sendSliderPosition), userInfo: nil, repeats: true)

}

func sendSliderPosition()
{
if sliderArray.count > 0
{
print(self.sliderArray.last)
sliderArray.removeLast()
}

}

Answer

Figured out the answer, thank to everyone for the help and suggestions:

override func viewDidLoad()
{
    super.viewDidLoad()

    NSTimer.scheduledTimerWithTimeInterval(0.02, target: self, selector: #selector(sendSliderPosition), userInfo: nil, repeats: true)
}

@IBAction func sliderValueChanged(sender: AnyObject)
{

    let step: Float = 1
    let roundedValue = round(slider.value / step) * step
    slider.value = roundedValue

    if sliderArray.first != slider.value
    {
        sliderArray.insert(slider.value, atIndex: 0)
    }

}

func sendSliderPosition()
{
    if sliderArray.count > 1
    {
        let end1 = sliderArray.count-2

        print(sliderArray[end1])

        sliderArray.removeLast()
    }

}

Explanation:

If the new slider value is different to the one already in the array then add it to the array at the start. Use an NSTimer to repeatedly call the sendSliderPosition function from viewDidLoad. The function will only be performed if there is more than one element in the array. If there is, print the element before the last one and remove the last. This always ensures that there is one element in the array so the function does not always run and that the element printed is the most recent one that hasn't already been printed.