ios - 从另一个文件调用函数时如何访问 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()
}
解决方案
在 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
//...
}
推荐阅读
- opengl - 计算到图形依赖项
- node.js - 部署使用 webpack 构建的新 React 应用程序
- javascript - (react.js)为什么会失去字段的价值以及为什么要重新渲染?
- sql - 在 SQL Server MERGE 语句的 MATCHED 子句中有一个 AND 运算符
- c# - OleDbDataReader 不读取最后一条记录
- c - 如何在 C 语言中禁用 Unix Socket 上的 Nagle 算法?
- ffmpeg - 如何使用 PyQt5 在 GUI 中流式传输视频?
- elasticsearch - 是否可以在 Elastic Search 中使用简单的查询字符串查询来设置 TYPE 参数
- jupyter-notebook - jupyter notebook (macOS) 中的 %conda list biopython 错误
- java - 无法加载类“com.intellij.util.Consumer”