Need Help: Automatically resets when changing the text of UILabel
wakune opened this issue · comments
Thanks for your beautiful slider, I'm using it for my Swift class assignment.
Here's my question:
When I tried to build something just like your demo GIF, where the slider controls the text of the UILabel, I found it quite difficult to make one. Since I had to use auto layout for adaptivity, I had a UIView to contain the slider. I wrote some lines of codes based on your given 'Usage' example, and I found it unable to control the text of the UILabel. When I tried to move the slider, it just reset itself to the initiate state while not change a thing. however, it was not completely not working since it run smoothly if I just wrap some print command in the function.
P.S., I found that there is some unexpected part of the slider (color is the same as the middle of the slider) on the right padding of the UIView, and I drew CGRect to cover it up. Hope there is a better way to avoid this.
Here's my code of the ViewController.
import UIKit
import SnappingSlider
class ViewController: UIViewController, SnappingSliderDelegate {
@IBOutlet weak var sliderView: SliderView!
@IBOutlet weak var hoursLabel: UILabel!
override func viewDidLayoutSubviews() {
let sliderLength = sliderView.frame.size.width
let sliderWidth = sliderView.frame.size.height
let slider = SnappingSlider(frame: CGRectMake(0.0, 0.0, sliderLength, sliderWidth), title: "Working Time")
slider.delegate = self
let sliderMask = UIView(frame: CGRectMake(sliderLength,0.0,40,50)) // sliderMask is used to cover the unexpected part
sliderMask.backgroundColor=UIColor.whiteColor()
sliderView.addSubview(slider)
sliderView.addSubview(sliderMask)
hoursLabel.text = "3"
}
func hoursChange(symbol: String) {
let a = Int(hoursLabel.text!)!
let b = 1
if symbol == "+" {
hoursLabel.text = "\(a+b)"
// print("\(a+b)") // run smoothly if the previous line is commented while this line is not commented
} else if symbol == "-" {
hoursLabel.text = "\(a-b)"
// print("\(a-b)") // run smoothly if the previous line is commented while this line is not commented
}
}
func snappingSliderDidIncrementValue(snapSwitch: SnappingSlider) {
hoursChange("+")
}
func snappingSliderDidDecrementValue(snapSwitch: SnappingSlider) {
hoursChange("-")
}
}
Thanks for your help!
It looks like you're creating and adding sliders inside the incorrect method. Have a look through the example project provided and pay close attention to the methods inside which the adding of subviews is taking place in. viewDidLayoutSubviews()
should only be used to recalculate any frame and point changes.