我正在尝试将我的大部分代码移到另一个文件中;我相信我已经这样做了,但是,我在调用函数时遇到了麻烦。
我有两个文件:
scannerBrain.swift
var parentView = UIViewController()
func startScan(){
//The code I want to execute is here
}
scannerViewController.swift
let scanner = scannerBrain()
scanner.parentView = self
let rightButton = UIBarButtonItem(barButtonSystemItem: .add, target: scanner, action: #selector(scanner.startScan))
navigationItem.rightBarButtonItem = rightButton
这个编译很好,除了startScan
从未被调用。我尝试将rightButton
的目标更改为self
,但这导致了unrecognised selector sent to instance
感谢任何帮助
答案 0 :(得分:1)
scanner
应为类级属性,否则将被释放。这样的事情。
class TestViewController: UIViewController {
let scanner = scannerBrain()
override func viewDidLoad() {
super.viewDidLoad()
scanner.parentView = self
let rightButton = UIBarButtonItem(barButtonSystemItem: .add, target: scanner, action: #selector(scanner.startScan))
navigationItem.rightBarButtonItem = rightButton
}
}