我有一个名为 colorChangerViewClass
的自定义类,它继承自 UIView
:
class colorChangerViewClass: UIView {
@IBOutlet weak var controller: ViewController!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// I want to change a textLabel in the main ViewController based on the current finger position here!
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// And here aswell!
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { ... }
func setColor(color: UIColor) {
self.backgroundColor = color
}
}
在 touchesBegan
和 touchesMoved
方法中,我想根据当前手指更改主 ViewController(不同的)中的 textLabel
位置。
在 colorChangerViewClass
和 ViewController
这两个类之间建立通信的最佳方式是什么?
最佳答案
在您的情况下,您正在尝试与 child 沟通,您可以通过多种方式获得所需的输出。
1.授权
<强>2。通知
<强>3。将父实例对象传递给子对象(类似于委托(delegate))
我正在用委托(delegate)进行演示,您可以将委托(delegate)用作:-
<强>1。声明 在 ColorChangerViewClass 之外的某处声明一个协议(protocol)
protocol ColorChangerViewClassDelegate:class {
func fingerDidMoved()
}
<强>2。在 ColorChangerViewClass 中创建委托(delegate)变量
class ColorChangerViewClass: UIView {
//declare delegate var
weak var delegate:ColorChangerViewClassDelegate?
@IBOutlet weak var controller: ViewController!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// I want to change a textLabel in the main ViewController based on the current finger position here!
self.notify()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.notify()
// And here aswell!
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
func setColor(color: UIColor) {
self.backgroundColor = color
}
func notify() {
if let delegate = self.delegate {
delegate.fingerDidMoved()
}
}
}
<强>3。将您的 View 委托(delegate)给 Controller
class SomeVC:UIViewController,ColorChangerViewClassDelegate {
var myLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
//your view
let theView = ColorChangerViewClass() // you might need auto layout or frame declared on your view to define view size
theView.delegate = self
}
//MARK:-deleate method of view
func fingerDidMoved() {
// set text from here
self.myLabel.text = "Your text"
}
}
关于ios - 从不同的 View 更改 View textLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43494536/