我有 2 个 View Controller 类。我想从 ViewController 调用 ViewController2 的方法,但是控制台给我这个错误:
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
这是我在 ViewController 类中的方法:
class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {
@IBAction func testButton(sender: AnyObject) {
ViewController2().setText("It's a Test!")
}
}
这是来自 ViewController2 的一些代码:
class ViewController2: UIViewController {
@IBOutlet weak var directionsTextField: UITextView!
func setText(var fieldText:String){
directionsTextField.text = directionsTextField.text + "\n \n" + fieldText
}
}
如果有任何帮助,我会很高兴! :-)
提前谢谢你:)
编辑:
我也明白了:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
关于 setText 方法...
好像 directionsTextField
还没有可能(??)
最佳答案
您已经非常接近自己弄清楚了。崩溃是因为您的 directionsTextField
尚不存在。作为一个 IBOutlet,它不会在调用 viewDidLoad
之前存在。你如何解决这个问题?
您为 SecondViewController
更改 API,并为其提供 directionsText
属性。以这样的方式结束:
@IBOutlet weak var directionsTextField: UITextView!
var directionsText = ""
override func viewDidLoad() {
super.viewDidLoad()
directionsTextField.text = directionsTextField.text + "\n\n\(directionsText)"
}
在您的 FirstViewController
中,您更改 IBAction 以匹配 SecondViewController
的新 API:
@IBAction func testButton(sender: AnyObject) {
let secondController = SecondViewController() // Felt a bit odd creating an instance without having a way of referencing it afterwards.
secondController.directionsText = "It's a test"
// Do what you want. (Perhaps pushing your secondController)
}
关于ios - 从 Swift 中的其他类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32428766/