简体   繁体   中英

Cannot assign value of type String to type UILabel

I have marked the part of my code where the problem is, it is commented out. The error message is:

Cannot assign value of type String! to type UILabel!.

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SendDataSegue" {
        if let sendToDetailViewController = segue.destinationViewController as? DetailViewController {
            var sendingText = metadataObj.stringValue
            sendToDetailViewController.messageLabelDos = sendingText
        }
    }
}

The label it should be changing is in my DetailViewController and it is a label. The code above is from my original ViewController. How can I make this work?

More code to put in context:

if metadataObj.stringValue != nil {

dispatch_async(dispatch_get_main_queue()) {
    self.performSegueWithIdentifier("SendDataSegue", sender: self)
}

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SendDataSegue" {
        if let sendToDetailViewController = segue.destinationViewController as? DetailViewController {
            var sendingText = metadataObj.stringValue
            sendToDetailViewController.viaSegue = sendingText
        }
    }
}

You need to pass the String instead of setting text to label, because when you correct it and set like this sendToDetailViewController.messageLabelDos.text = sendingText , you will get nil error because messageLabelDos is not initialize yet, so try like this. Create one string instance in DetailViewController and use that inside prepareForSegue for passing String and then use that String instance in viewDidLoad to assign Label to text.

class ViewController: UIViewController { 

    //Your other methods

    func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
        if segue.identifier == "SendDataSegue" {
            if let sendToDetailViewController = segue.destinationViewController as? DetailViewController {
                var sendingText = metadataObj.stringValue
                sendToDetailViewController.messageDos = sendingText
            }
        }
    }
}

Inside DetailViewController

var messageDos: String = ""

override func viewDidLoad() {
    super.viewDidLoad()
    self.messageLabelDos.text = messageDos
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM