adjusting label to slider value swift

放肆的年华 提交于 2019-11-29 16:48:46

问题


I have a slider and label in my swift project. On the storyboard, I control dragged my slider onto my controller class for that page and created an outlet and also an action. I control dragged another label as an outlet. I am trying to update the label based on the slider's value. I don't know where i am going wrong.

Code:

@IBOutlet weak var slider: UISlider!

@IBOutlet weak var sliderVal: UILabel!

@IBAction func sliderValueChanged(sender: UISlider) {
    var currentValue = Int(sender.value)
    println("Slider changing to \(currentValue) ?")
    sliderVal.text = "\(currentValue) Km"
} 

I can see in the log the sliderValueChanged funciton is being called and the log is printing the value but the label's text is not updating. What am I doing wrong?

Update:

I just put a slider object and label on my login screen and used the same methodology and code to change the label text and it worked but it will not work inside my tab bar controller. Does this shed any light on what the issue may be?


回答1:


Update the slider value in Main queue

@IBAction func sliderValueChanged(sender: UISlider) {
    var currentValue = Int(sender.value)
    println("Slider changing to \(currentValue) ?")
    dispatch_async(dispatch_get_main_queue(){
        sliderVal.text = "\(currentValue) Km"
    })
}

I hope this is helpful to you.




回答2:


try this

    var currentValue = Int(slider.value)
    println("Slider changing to \(currentValue) ?")
    startTime.text = "\(currentValue) Km"



回答3:


class ViewController: UIViewController {

@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var slideroutlet: UISlider!
@IBOutlet weak var lblValue: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func slider(_ sender: Any) {

    lblValue.text = String(slideroutlet.value)
    imgView.alpha = CGFloat(slideroutlet.value)
}



回答4:


Swift 3: Select .allEvents for its UIControlEvents.

slider.addTarget(self, action: #selector(ViewController.updateKmsLabel(sender:)), for: .allEvents)
// To use
func updateKmsLabel(sender: UISlider!) {
    let value = Int(sender.value)
    DispatchQueue.main.async {
        self.kmsLabel.text = "\(value)"
        print("Slider value = \(value)")
    }
}



回答5:


If you want to do it programmatically, this is one way.

var slider: UISlider()
var label: UILabel()

func numberValueChanged(sender: UISlider) {
    slider.setValue(Float(Int(slider.value)), animated: true)
    updateLabels(slider.value)
}
fun updateLabels(nV: Float?) {
    if let v = nV {
        self.label.text = "\(v)"
    }
}

slider.addTarget (self,
                 action: #selector(numberValueChanged)
                 forControlEvents: UIControlEvents.ValueChanged
)

Hope this was helpful :)



来源:https://stackoverflow.com/questions/30639675/adjusting-label-to-slider-value-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!