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

时间:2022-04-02 16:44:46

I'm trying to move a big chunk of my code to another file; I believe I have done this, however, I'm having trouble calling a function.

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

I have two files:

我有两个文件:

scannerBrain.swift

scannerBrain.swift

var parentView = UIViewController()

func startScan(){
//The code I want to execute is here
}

scannerViewController.swift

scannerViewController.swift

let scanner = scannerBrain()
scanner.parentView = self
let rightButton = UIBarButtonItem(barButtonSystemItem: .add, target: scanner, action: #selector(scanner.startScan))
navigationItem.rightBarButtonItem = rightButton

This compiles fine, except startScan is never called. I tried changing the rightButton's target to self, but that caused a crash of an unrecognised selector sent to instance

编译很好,除了从不调用startScan。我尝试将rightButton的目标更改为self,但这导致发送到实例的无法识别的选择器崩溃

Appreciate any help

感谢任何帮助

1 个解决方案

#1


1  

scanner should be class level property, otherwise it will be released. Something like this.

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

#1


1  

scanner should be class level property, otherwise it will be released. Something like this.

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