情况:我通过在 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/