尝试在视图控制器外部使用文本视图时出错

时间:2015-05-04 13:44:57

标签: swift uitextview viewcontroller optional

我收到了错误:

  

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

每当我尝试将文本添加到视图控制器之外的文本视图(bottomTextView)时。我的文本视图链接到我的主视图控制器。我有另一个名为Checkbox(UIButton的子类)的类,它尝试使用以下方法将文本添加到文本视图中:

var main_vc = ViewController()
main_vc.bottomTextView.insertText("Checked")

但是,在我的视图控制器中使用以下内容时没有问题:

bottomTextView.insertText("Checked")

我无法弄清楚为什么会这样以及如何解决它。谢谢!

编辑:

我的Checkbox类是UIButton的子类,它有一个方法,只要单击一个复选框就会调用该方法。单击该复选框时,我想将文本添加到主视图控制器内的文本视图中。

2 个答案:

答案 0 :(得分:1)

如果您正在使用Storyboard;

var storyboard = UIStoryboard(name: "Main", bundle: nil)
var main_vc = storyboard.instantiateViewControllerWithIdentifier("ViewControllerIdentifier") as! ViewController
main_vc.bottomTextView.insertText("Checked")

答案 1 :(得分:1)

我怀疑你的问题是你在呈现视图控制器之前尝试从另一个视图控制器访问bottomTextView(例如使用segue)。在这种情况下,您的ViewControllerIBOutlet都没有设置,因此您收到了该错误。

我认为你以错误的方式考虑这个问题 - 视图控制器不应该直接编辑另一个视图控制器的视图。相反,您可以在bottomTextView中设置应该显示在prepareForSegue中的文字。例如,假设这是您的ViewController类:

class ViewController : UIViewController {
    var yourText: String = ""
    @IBOutlet var bottomTextView: UITextView!

    override func viewDidLoad() {
        // In viewDidLoad all the outlets have been set so you won't get any errors
        // setting the text.
        bottomTextView.text = yourText
    }
}

这是您想要移动的另一个视图控制器,转移到ViewController的实例:

class AnotherViewControler : UIViewController{
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if let vc = segue.destinationViewController as? ViewController 
           where segue.identifier == "YourSegueID" {

            vc.yourText = "SomeText"
        }
    }
}

有关在视图控制器之间传递数据的更多信息,请查看以下问题:How do you share data between view controllers and other objects in Swift?

相关问题