user6631314
user6631314

Reputation: 1958

IOS/Swift: Set text of label with IBOutlet

I am having trouble with the elementary task of setting the text of a label.

The label is wired from storyBoard to an IBOutlet. When I try to set the text of the label with the following code it gives the error: Expected Declaration

@IBOutlet weak var myLabel: UILabel!


var someText: String = "Some text"
self.myLabel.text = someText

If I change self.myLabel to... let self.myLabel... it gives error: Expected pattern

What is the proper syntax to set the label text?

Upvotes: 2

Views: 2647

Answers (1)

Optimus
Optimus

Reputation: 810

In the given example you cannot use the property of outlet example .text directly outside of any method. to do it correctly you need to create a method or you can use predefine method for example viewDidLoad()

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

          self.myLabel.text = someText

    }

or

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

          setTextOfLabel()

    }

func setTextOfLabel(){

  self.myLabel.text = someText
}

Upvotes: 3

Related Questions