UIBarButtonItem在点击时不会在另一个类中调用函数

时间:2017-07-16 06:48:20

标签: ios swift

我正在尝试将我的大部分代码移到另一个文件中;我相信我已经这样做了,但是,我在调用函数时遇到了麻烦。

我有两个文件:

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

的崩溃

感谢任何帮助

1 个答案:

答案 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
    }
}