Swift:无法通过使用发送者的 segue 设置 [String]

Posted

技术标签:

【中文标题】Swift:无法通过使用发送者的 segue 设置 [String]【英文标题】:Swift: Failing to set a [String] through a segue using the sender 【发布时间】:2018-07-16 11:58:45 【问题描述】:

美好的一天。我正在创建自己的第一个应用程序并遇到了问题。我有一个带有可点击内容的 AR 场景,当您触摸它们时,segue 会触发 ViewController 并根据屏幕上触摸的内容设置视图控制器标签和文本视图。

说明: 1. CaseViewController 是目标视图控制器。 2. "artNews" 和 "politicalNews" 是字符串数组,我在其中写了 3 个字符串,它们被定义并且永远不会为 nil。

问题:由于 segueInputText 为 nil,我遇到了崩溃。为什么它会变成 nil,我该如何纠正它?

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) 

    let destinationVC = segue.destination as! CaseViewController
    destinationVC.segueInputText = sender as? [String]

    print("\(String(describing: sender))")


override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) 

    guard let touchLocation = touches.first?.location(in: sceneView),
        let hitNode = sceneView?.hitTest(touchLocation, options: nil).first?.node,
        let nodeName = hitNode.name
        else  return 

    if nodeName == imageNameArray[0] 

        performSegue(withIdentifier: "CaseViewController", sender: artNews)

     else 
        print("Found no node connected to \(nodeName)")
        return
    

    if nodeName == imageNameArray[1] 

        performSegue(withIdentifier: "CaseViewController", sender: politicalNews)

     else 
        print("Found no node connected to \(nodeName)")
        return
    

CaseViewController 连接了 UILabels 和 UITextViews 并且这个:

    var segueInputText : [String]? 
    didSet 
        setupText()
    


    func setupText() 

    // Why are these values nil? 
    testLabel.text = segueInputText![0]
    ingressLabel.text = segueInputText![1]
    breadLabel.text = segueInputText![2]

    testLabel.reloadInputViews()
    ingressLabel.reloadInputViews()
    breadLabel.reloadInputViews() //breadLabel is a UITextView

感谢您阅读我的问题! 亲切的问候。

【问题讨论】:

【参考方案1】:

删除 didSet 块,因为当您在 prepare 中设置数组时,观察触发器并且 lbl 仍然是 nil

func setupText() 
   if testLabel == nil  // if one is nil then all of them too
     return 
   
 

【讨论】:

您应该改为从viewWillAppear 中调用setupText。然后,你也可以跳过 if 语句。【参考方案2】:

在这种情况下不要使用didSet 观察者。它永远不会起作用。

setupText() IBOutlets 中被访问,但在调用prepare(for 时尚未连接。


移除观察者

var segueInputText : [String]?

并在viewWillAppear 中致电setupText

override func viewWillAppear(_ animated: Bool) 
    super.viewWillAppear(animated)
    setupText()

【讨论】:

“不要使用r the” - 可能是错字?【参考方案3】:

在你这样做的那一刻:

destinationVC.segueInputText = sender as? [String]

目标视图控制器尚未加载,因此没有连接任何插座,因此访问它们中的任何一个都会使您的应用程序崩溃,因为它们仍然为零。

您必须将要传递给目标控制器的任何值分配给一个属性,并将该属性的值分配给viewDidLoad 中的相应插座。这样可以确保所有插座都已连接。

出于同样的原因,不要使用属性观察器将属性的值分配给任何标签,因为这会再次发生,在视图控制器有机会加载之前......

【讨论】:

以上是关于Swift:无法通过使用发送者的 segue 设置 [String]的主要内容,如果未能解决你的问题,请参考以下文章

执行 segue swift 4

使用 Swift 2.0 在 segue 之间传递数据

通过 Segue 传递数据(swift 2)

Swift - 在 segue 之后保存 ViewController 设置

人工触发 Segue

使用 Swift 在没有情节提要的情况下展开 segue