首页 > 解决方案 > 从另一个文件调用函数时如何访问 ViewController 中的 UIView?

问题描述

情况:我通过单击子视图的按钮来绘制东西。然后我将子视图添加到视图中。

问题:drawNew从另一个 swift 文件调用时,if-loop不会触发。可能是因为没有找到view带有标签的。777

问题:如何告诉代码view在 ViewController 中查找?

我什么时候调用这个函数drawNew()我从另一个文件中调用它override func touchesEnded(...)

//###########################
//  ViewController.swift    
//###########################
var dv = Painting() // in here are functions to create a cg path

//
// IBActions
//
@IBAction func buttonPressed(_ sender: UIButton) {
   // painting
    if sender.tag == 1 {
      drawNew()
    } else if sender.tag == 2 {
        CanvasView.clearCanvas()
    }

}

//
// FUNCTIONS
//
func drawNew() {
    dv.makeMeSomePath()
    if let foundView = view.viewWithTag(777) { // problem lies here maybe
        dv.tag = 111
        foundView.addSubview(dv)
        print("added subview")
    }
}

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // prepare the canvas for
        let newView = CharacterView(frame: CGRect(x: 0,
                                              y:0,
                                              width: HandwritingCanvasView.frame.width,
                                              height: HandwritingCanvasView.frame.height))

        newView.tag = 777
        HandwritingCanvasView.addSubview(newView)
//        self.view.addSubview(demoView)
    }

然后这是我调用drawNew()函数的另一个文件

//  HandwritingCanvasView.swift

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

     ViewController.drawNew()

}

标签: iosswiftuiview

解决方案


在 ViewController 中引用 newView 会更容易。

尝试下一步

//###########################
//  ViewController.swift    
//###########################
weak var subView: UIView? //Add reference on your view

//
// FUNCTIONS
//
func drawNew() {
   dv.makeMeSomePath()
   if let foundView = subView { // Use the reference instead of searching view with tag
       dv.tag = 111
       foundView.addSubview(dv)
       print("added subview")
   }
 }


override func viewDidAppear(_ animated: Bool) {
    // Your code is here
    // ...
    HandwritingCanvasView.addSubview(newView)
    subView = newView
    //...
}

推荐阅读