我已经声明了一个变量tipPercentage
、一个UISlider Action tipSliderAction
和一个UILabel tipPercentageLabel
。
我还创建了一个 clear
函数,这样当我点击一个按钮时,以上所有内容都会重置为默认值。
这是代码:
var tipPercentage = 1
@IBOutlet weak var tipPercentageLabel: UILabel!
@IBOutlet weak var tipSlider: UISlider!
@IBAction func tipSliderAction(sender: UISlider) {
let currentValue = Int(sender.value)
tipPercentageLabel.text = ("\(currentValue)")
let percentage = Double(currentValue) / 100
tipPercentage = percentage
}
@IBAction private func clear(sender: UIButton) {
tipSlider.value = 10
tipPercentageLabel.text = String(tipSlider.value)
tipPercentage = tipSlider.value
clear
函数是我将值重置为默认值的地方。我想我的问题是,不是重置每个单独的变量,有没有办法只重置一个,然后所有其他变量都会自行更新?
例如,在 clear
函数中,当我将 tipSlider.value
设置为 10 时,tipPercentageLabel.text
和 tipPercentage
将在我不在 clear
函数中设置它们的情况下更新。
谢谢。
最佳答案
您可以通过为 UISlider 的 ValueChanged 事件添加一个处理程序来完成此操作。
override func viewDidLoad()
{
super.viewDidLoad()
tipSlider.addTarget(self, action: #selector(ViewController.onValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
}
@IBAction func onValueChanged(sender: AnyObject)
{
tipPercentageLabel.text = String(tipSlider.value)
tipPercentage = tipSlider.value
}
关于ios - uislider 值和变量,Swift 中的标签关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38987571/