Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Increment slider value #42

Open
saikodiabovic opened this issue Jan 27, 2020 · 2 comments
Open

Increment slider value #42

saikodiabovic opened this issue Jan 27, 2020 · 2 comments

Comments

@saikodiabovic
Copy link

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?

@juanjovn
Copy link

juanjovn commented Mar 19, 2020

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

@juanjovn
Copy link

juanjovn commented Mar 20, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants