uislider 值与变量、标签关联 Swift
uislider value and variable, label association in Swift
我已经声明了一个变量 tipPercentage
、一个 UISlider 动作 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
}
可以通过UISlider的ValueChanged事件实现
UIControlEvents.ValueChanged 事件操作
@IBAction func onValueChanged(sender: AnyObject)
{
tipPercentageLabel.text = String(tipSlider.value)
tipPercentage = tipSlider.value
}
现在在清除按钮操作中将 UISlider 值设置为默认值,它将立即调用 UISlider 的 ValueChanged 操作并重置所有值。
我已经声明了一个变量 tipPercentage
、一个 UISlider 动作 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
}
可以通过UISlider的ValueChanged事件实现
UIControlEvents.ValueChanged 事件操作
@IBAction func onValueChanged(sender: AnyObject)
{
tipPercentageLabel.text = String(tipSlider.value)
tipPercentage = tipSlider.value
}
现在在清除按钮操作中将 UISlider 值设置为默认值,它将立即调用 UISlider 的 ValueChanged 操作并重置所有值。