变量更改时更新 UILabel 文本 [英] Updating UILabel text when variable changes
问题描述
我有一个 UIControl 类,需要根据 UIImageView 位置进行一些计算,可以使用 touchesBegan 和 touchesMoved(该类中的所有内容)移动该位置.我想将它显示为我以编程方式创建的 UILabel.
I've got a UIControl class and need to do some calculation based on UIImageView location which can be moved with touchesBegan and touchesMoved (everything inside this class). Than I would like to display it as a UILabel which I've created programmatically.
class control : UIControl{
...
let leftControl: UIImageView = UIImageView(image: UIImage(named: "left-control"))
...
func leftValue() -> String{
var leftValue : String = "0.0"
leftValue = "\(leftControl.center.x)"
return leftValue
}
}
和我的 ViewController.swift
and my ViewController.swift
class ViewController: UIViewController {
class ViewController: UIViewController {
let ctrl : Control = Control()
let leftLabel : UILabel = UILabel(frame: CGRect(x: 40, y: 300, width: 150, height: 30))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ctrl.frame.origin = CGPoint(x: 40, y: 400)
leftLabel.text = "\(ctrl.leftValue())" //displays only starting value
view.addSubview(slider)
view.addSubview(leftLabel)
view.addSubview(rightLabel)
}
我知道它在 viewDidLoad 中,所以它没有正确更新.我想知道 scheduleTimer 但不知道它是否是好的解决方案.
I know that it's inside the viewDidLoad so it's not updating properly. I was wondering about scheduledTimer but don't know if it's good solution.
推荐答案
您可以使用协议和委托来实现这一点 - 在您的 Control
文件中添加:
You can achieve this using protocols and delegation - in the file for your Control
add this :
protocol ControlDelegate: class {
func controlPositionDidChange(leftValue: String)
}
并在 Control
类中添加一个 weak var 委托:ControlDelegate?
.
And add a weak var delegate: ControlDelegate?
inside Control
class.
在视图控制器的文件中进行以下更改:
In the file for view controller make following changes :
class ViewController: UIViewController, ControllDelegate {
let ctrl : Control = Control()
let leftLabel : UILabel = UILabel(frame: CGRect(x: 40, y: 300, width: 150, height: 30))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ctrl.frame.origin = CGPoint(x: 40, y: 400)
ctrl.delegate = self
leftLabel.text = "\(ctrl.leftValue())" //displays only starting value
view.addSubview(slider)
view.addSubview(leftLabel)
view.addSubview(rightLabel)
}
func controlPositionDidChange(leftValue: String) {
leftLabel.text = leftValue
}
}
现在,每当您想通知委托您的控件已更改位置时,只需在适当的位置调用 self.delegate?.controlPositionDidChange(self.leftValue())
.
Now, whenever you want to inform the delegate that your control has changed the position, simply call self.delegate?.controlPositionDidChange(self.leftValue())
in appropriate places.
通常,有 更多在文档中.我强烈建议通读它们,因为委派和协议在 CocoaTouch 中被广泛使用.
As usually, there is more in the docs. I highly suggest reading through them as delegation and protocols are widely used in CocoaTouch.
这篇关于变量更改时更新 UILabel 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!