Search code examples
iosswiftwatchkitapple-watch

Giving a range to a variable type CGFloat


I am creating a custom slider in watchKit. I have one variable sliderPosition of type CGFloat which sets its position on UI on didSet. I change the value of slider using Digital Crown.

func didCrown(value: Double, rps: Double) {
        if isValidRange() {
            if value > 0 {
                ring.sliderPosition = ring.sliderPosition + 0.01
            } else if value < 0 {
                ring.sliderPosition = ring.sliderPosition - 0.01
            }
        }
    }

    func isValidRange() -> Bool {
        if ring.sliderPosition >= 0.00 && ring.sliderPosition <= 1.00 {
            return true
        } else if ring.sliderPosition <= 0.0 {
            ring.sliderPosition = 0
            return false
        } else {
            ring.sliderPosition = 1
            return false
        }
    }

I am looking for some native functions to give range to my var sliderPosition between 0 to 1.

In above method isValidRange there is some error in logic. Because when value is 1.00 and I try to increase the value it will set 1.01 and same for when 0.00 it sets -0.01.


Solution

  • As @ Martin R suggests, probably you are looking for -

     extension CGFloat {
        func clamp (min: CGFloat, _ max: CGFloat) -> CGFloat {
            return Swift.max(min, Swift.min(max, self))
        }
     } 
    

    and then use it like -

    func didCrown(value: Double, rps: Double) {
           if value > 0 {
                ring.sliderPosition = (ring.sliderPosition + 0.01).clamp(min: 0.0, 1.0)
             } else if value < 0 {
                 ring.sliderPosition = (ring.sliderPosition - 0.01).clamp(min: 0.0, 1.0)
         }
     }