Marlon Ou
Marlon Ou

Reputation: 491

Swift Accessing IBOutlet from another class

So I have got my view controller which has a IBOutlet property that gives the view controller access to an added view(A view dragged into view controller in the storyboard file, the view class also has a UILabel property outlet) I am trying to modify the text of uilabel in view class. First I tried directly using view.label.text = "some text", but it didn't work. Then I wrote a function in the view class to set the label text, magically it worked. Why doesn't the first way work while the second one does?

class Controller : UIViewController {

    @IBOutlet weak var answerResultView: AnswerResultView!

    @IBAction func button(sender : AnyObject){
        answerResultView.text = "some text" //this line doesn't work
        answerResultView.setText("some text")
    }
}

class TheView : UIView {

    @IBOutlet weak var label : UILabel!

    func setText(text : String){ 
        label.text = "Some text"
    }
}

Thanks so much for any answer

Upvotes: 2

Views: 2096

Answers (2)

Aruna Mudnoor
Aruna Mudnoor

Reputation: 4825

Try this

answerResultView.label.text = "some text"

Upvotes: 1

Sourabh Mahna
Sourabh Mahna

Reputation: 52

In the second way, you are calling the method of the view in which you set the text of the label.

First way is wrong as you are trying to set text of view instead of its label. Use

answerResultView.label.text = "some text"

Upvotes: 1

Related Questions