我有一个名为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
之间建立沟通的最佳方式是什么?
答案 0 :(得分:1)
您太靠近无法解决问题,您需要设置ViewController
的{{1}}到controller
属性的引用。也无需将colorChangerViewClass
声明为出口,因此请更改下面的声明。
controller
现在var controller: ViewController?
和touchesBegan
使用此控制器访问touchesMoved
textLabel
现在,您正在创建override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.controller?.textLabel.text = //set text
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.controller?.textLabel.text = //set text
}
对象的ViewController
班级中设置colorChangerViewClass
属性。
controller
注意:班级名称始终以大写字母开头,因此如果您将班级名称从@IOutlet var colorView: colorChangerViewClass!
//set controller property in viewDidLoad
colorView.controller = self
更改为ColorChangerViewClass
,则会更好。
答案 1 :(得分:1)
在你的情况下,你正试图将孩子传达给父母,有几种方法可以让你获得所需的外出。
<强> 1.Delegation 强>
<强> 2。通知强>
第3。将父实例对象传递给子代理(类似于委托)
我正在与代表进行演示,您可以将委托用作: -
<强> 1。声明强> 在ColorChangerViewClass
旁边的某处声明协议protocol ColorChangerViewClassDelegate:class {
func fingerDidMoved()
}
<强> 2。在ColorChangerViewClass中创建委托var
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。将视图的代理设置为控制器
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"
}
}