通过Segue

时间:2017-02-07 09:45:30

标签: ios swift uitextview segue uistoryboardsegue

我正在尝试将文本从其他ViewController传递给TextView

    if (segue.identifier == "HomeToDetails") {
        let nav = segue.destination as! UINavigationController
        let nextVC = nav.topViewController as! DetailsViewController
        nextVC.infoTextView.text = "TESTING"
    }

但它崩溃了:

  

致命错误:在解包可选值时意外发现nil

7 个答案:

答案 0 :(得分:1)

UITextField中无法在DestinationViewController prepareForSegue:sender上设置文本,因为在加载视图之前,未初始化最近分配的控制器的所有视图组件(此时,它们都是零),它们只会在加载DestinationViewController视图时出现。

您需要在infoString中使用可选变量DetailsViewController,您可以在prepareForSegue方法中设置

if (segue.identifier == "HomeToDetails") {
        let nav = segue.destination as! UINavigationController
        let nextVC = nav.topViewController as! DetailsViewController
        nextVC.infoString = "TESTING"
}
DetailsViewController.swift

中的

class DetailViewController: UIViewController {

  var infoString: String?

  override func viewDidLoad() {
     super.viewDidLoad()

     if let info = infoString {
         self.infoTextView.text = info
     }
   }

}

答案 1 :(得分:0)

如果值为nil并且您打开它,那么应用程序将崩溃,您应该使用可选绑定以避免崩溃。

if (strpos($string, '<video')){
   echo $string;
}

答案 2 :(得分:0)

检查一下:

if (segue.identifier == "HomeToDetails") {

    // get a reference to the second view controller
    let secondViewController = segue.destination as! DetailsViewController

    // set a variable in the second view controller with the String to pass
    secondViewController.infoTextView.text = "TESTING"
}

答案 3 :(得分:0)

试试这段代码:

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if let nav = segue.destination as? UINavigationController {
            if let nextVC = nav.topViewController as? DetailsViewController {
             nextVC.infoTextView.text = "Data you want to pass"
            }
        }
     }

答案 4 :(得分:0)

这是因为当您为文本视图赋值时,文本视图未被初始化,因为尚未调用下一个类的viewDidLoad。所以只传递字符串,然后在下一个类的viewDidLoad中设置文本。

答案 5 :(得分:0)

在创建文本之前,您无法在另一个视图中直接将文字传递给TextView

First ViewController:

if (segue.identifier == "HomeToDetails") {
let secondViewController = segue.destination as! DetailsViewController
secondViewController.myText = "TESTING"
}

<强> DetailsViewController:

var myText = ""
override func viewDidLoad() {
super.viewDidLoad()
infoTextView.text = myText
}

答案 6 :(得分:0)

在加载视图之前,不会初始化DetailsViewController的所有视图组件。您可以在将值分配给该视图的组件之前加载该视图

考虑vC是视图控制器,它包含您要加载的视图。然后

if let _ = vC.view {

      //Assign value here
}

加载视图后,我们可以将值设置为该视图中的组件。在SWIFT 3中

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

    if segue.identifier == "HomeToDetails" {

        let nav = segue.destination as! UINavigationController
        let nextVC = nav.topViewController as! DetailsViewController
        if let _ = nextVC.view {
            nextVC.infoTextView.text = "TESTING"
        }
    }
}