Roi Mulia Roi Mulia - 3 months ago 25
iOS Question

Use UISlider to get integer value in range

I'm trying to solve this issue in the most accurate way.

I have a

UISlider
, and a range between
0 to 300
(All primes).

How can I, using the
UISlider
, get an accurate access to each prime number in this range, while moving the slider? Any thoughts?

Answer

Store the first 0-300 prime numbers in an array

Bad way of doing it. Set slider min to 0, and max to 300, and current to 0

When moving the slider check if the slider number exists in the array, if it does, update the label's text with the prime number

let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293]

@IBOutlet weak var label: UILabel!
@IBAction func slider(sender: UISlider) {
    let sliderNumber = Int(sender.value)
    if primes.contains(sliderNumber) {
        label.text = "\(sliderNumber)"
    }
}

Good way to do it. Set slider min to 0, and max to 61, and current to 0. There are 62 prime numbers in the first 0-300. When moving the slider, change the label text by indexing the primes array.

let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293]

@IBOutlet weak var label: UILabel!
@IBAction func slider(sender: UISlider) {
    let sliderNumber = Int(sender.value)
    label.text = String(primes[sliderNumber])
}

Tested both the first and this second implementation, and the second one is much cleaner on the value transition.

Comments