ios - 从另一个文件调用函数时如何访问ViewController中的UIView?

标签 ios swift uiview

情况:我通过在 subview 上单击按钮来绘制内容。然后我将 subview 添加到 View 中。

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

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

什么时候调用函数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()

}

最佳答案

在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
    //...
}

关于ios - 从另一个文件调用函数时如何访问ViewController中的UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53468032/

相关文章:

ios - 在 Realm 迁移期间创建 Realm 对象

ios - WKWebView 添加到 subview

ios - 将 View 添加到 NativeScript ActionBar 会破坏导航

php - 如何将我自己的日历与我的手机(iPhone、Android 等)同步

iphone - MPMoviePlayerViewController 视频时长

ios - 如何将 swift CLlocation 纬度和经度传递给 wkwebview ajax 函数或 Controller 函数

ios - UITabBarController 顶部、底部、前导、尾随的额外空间

ios - UIView水平动画不水平

javascript - iOS ui 隐藏页面底部。当隐藏和显示 iOS 底部菜单时,如何使整个页面响应并使其底部始终可见?

ios - glDrawArrays(GL_POINTS, 0 4) 在 iOS 5.0 和 openGL ES 2.0 中不绘制点