ios - 从 Swift 中的其他类调用方法

标签 ios xcode swift instantiation

我有 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/

相关文章:

ios - AVPlayer HLS 直播流 IOS

objective-c - IBOutletCollection 在 Interface Builder 中设置排序

json - 为什么我不能使用 codable 解码这个 json 数据?

swift - 执行 usdzconvert -h 并获取 env : python 3. 7 找不到此类文件或目录

ios - 如何快速测量带宽

swift - 如何运行 shell 命令并让它在命令运行时打印输出?

ios - #<UIButton :0xa7f1390> 的未定义方法 `selected'

objective-c - UIButtons 不工作

ios - 如何在 UILabel 中的不同字符串上显示两个单独的链接?

ios - Xcode:错误:无法使用重复的目标启动。原始目标在 Xcode/gdb 中运行良好