在prepareForSegue中设置destinationviewcontroller的标签文本会引发错误:在解包时意外发现nil可选值

时间:2015-07-08 04:02:30

标签: ios swift

我确定字符串不是nil并且标签存在,我试图找出标签中的文本为零的原因。 destinationViewController的其他成员设置正确,但只要我添加行来设置标签,程序就会崩溃。

// Mark segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get reference to the destination view controller
    var detailVC = segue.destinationViewController as! DetailViewController
    var detailImages: Array<UIImage> = []
    detailImages.append(UIImage(named: "pup.jpg")!)
    detailImages.append(UIImage(named: "dog.png")!)
    // Set the property to the selected location so when the view for
    // detail view controller loads, it can access that property to get the feeditem obj
    detailVC.selectedLocation = _selectedLocation;
    println(_str!)
    detailVC.myLabel.text = "hello"
}

2 个答案:

答案 0 :(得分:5)

这是因为myLabel的出口不会在prepareForSegue中设置,因此它将为零。请尝试以下方法,

DetailViewController中创建一个字符串var,

var labelText: String?
prepareForSegue

中的

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get reference to the destination view controller
    var detailVC = segue.destinationViewController as! DetailViewController
    var detailImages: Array<UIImage> = []
    detailImages.append(UIImage(named: "pup.jpg")!)
    detailImages.append(UIImage(named: "dog.png")!)
    // Set the property to the selected location so when the view for
    // detail view controller loads, it can access that property to get the feeditem obj
    detailVC.selectedLocation = _selectedLocation;
    println(_str!)
    detailVC.labelText = "hello"
}

并在DetailViewController

的viewDidLoad中
override func viewDidLoad() {
    super.viewDidLoad()

    self.myLabel.text = labelText
    // Do any additional setup after loading the view.
}

答案 1 :(得分:0)

是的,最后我将prepareForSegue中的最后一行更改为

detailVC.myString = _str as? String

我不确定我是不是?因为在我的detailVC中我添加了:

var myString:String?

将NSString转换为String的最佳位置在哪里,或者无关紧要? 谢谢!