Patrick Lee
Patrick Lee

Reputation: 37

'[UILabel]' does not have a member named 'text'

After I upgrade to Xcode 6.3, it is failed to assign the String into the UILabel. I got the Swift compiler error message "'[UILabel]' does not have a member named 'text'" on UILabel textLabel. Any idea to fix it?

import UIKit

class ViewController: UIViewController {

    @IBOutlet var nameTxt: [UITextField]!
    @IBOutlet var textLabel: [UILabel]!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func changeLabel(sender: UIButton) {
        self.textLabel?.text = "Success"
    }
}

Upvotes: 2

Views: 857

Answers (1)

nhgrif
nhgrif

Reputation: 62072

When we are hooking up labels (or anything else) from the storyboard to our source code, we will get a pop-up menu that looks something like this:

enter image description here

When you click "Connect" here (all I did after getting the pop-up is type "textLabel", everything else is default), it will produce the following line of code:

@IBOutlet weak var textLabel: UILabel!

However, "Outlet" is not the only option for connecting our objects from interface builder to source code.

If we change the "Connection" drop down to select "Outlet Collection", like so:

enter image description here

Then the line of code generated will match exactly the line of code in your question:

@IBOutlet var textLabel: [UILabel]!

We've created an array of labels. This is useful in some cases, but perhaps not what we actually want here.

In order to fix this, we must first be sure to unhook our original connection (otherwise, we'll have runtime exceptions).

So, if you go back to Interface Builder and right click on the label in question, you'll receive a menu that looks like this:

enter image description here

Notice how the label is linked to a "Referencing Outlet Collection", but not a "Referencing Outlet"? This is what we need to fix. So, click the X for that connection to unlink it. Now we can go to the source code and delete the @IBOutlet that was generated.

Now, rehook your label up as a regular "Outlet" and not an "Outlet Collection", and your changeLabel method will work perfectly fine as-is.

When your label is correctly hooked up as an "Outlet" rather than an "Outlet Collection", your interface builder right click menu will look like this:

enter image description here

(Notice the difference between this one and the previous image.)

Upvotes: 2

Related Questions