Ramotion / fluid-slider

:octocat:💧 A slider widget with a popup bubble displaying the precise value selected. Swift UI library made by @Ramotion

Home Page:https://www.ramotion.com/fluid-slider/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Increment slider value

saikodiabovic opened this issue · comments

I am looking to add a way to use increments of 5. So if I had max set to 100, it would jump 5, 10, 15... 85, 90,95 , 100 and allow no other values. Is there any way to currently do this or an easy way to add this functionality?

I am looking for the same behaviour. Have you already solved it?

I found a solution that worked for me:
First of all I defined a round function:

func roundTo(n: Float, mult: Int) -> Int{ let result: Float = n / Float(mult) return Int(result.rounded()) * mult }

Then, before adding the slider subview I call the target-action for value changed:

slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged)

This target action calls this fuction that is suitable for me but I guess is the same behaviour you need:

@objc func sliderValueChanged(_ sender: UIControl){
        let fractionValue = slider.fraction

        // In my case I use 180 as max value and 10 as min value.
        // You need to change this values to your requirements.
        // My slider goes from 10 to 180 in steps of 5 units.

        let value: Float = Float(fractionValue * (180 - 10)) 
        let resultValue: Int = 10 + roundTo(n: value, mult: 5)
        let nobShadow = NSShadow()
        nobShadow.shadowOffset = .init(width: 0, height: 1)
        let sliderNobLabelAttributes: [NSAttributedString.Key: Any] = [
            .font: UIFont(name: "Avenir Next Medium", size: 20)!,
            .foregroundColor: #colorLiteral(red: 0.1333333333, green: 0.2196078431, blue: 0.262745098, alpha: 1),
            .shadow: nobShadow
        ]
        let attributedString = NSAttributedString(string: String(resultValue), attributes: sliderNobLabelAttributes)
        
        slider.attributedTextForFraction = { fractionValue in
            return attributedString
        }
    }

I hope this help you! 🙂
Best regards.