UIView viewwithtag method in swift

40,057

Solution 1

You need to use a typecast. This code will do it:

    if let theLabel = self.view.viewWithTag(123) as? UILabel {
        theLabel.text = "some text"
    }

Solution 2

viewWithTag: returns a UIView, you need to typecast it to UILabel.

var yourLabel : UILabel = yourView.viewWithTag(yourTag) as! UILabel;

Solution 3

You need to write as

var getMyLabel : UILabel = self.view.viewWithTag(tagValue) as UILabel;
Share:
40,057

Related videos on Youtube

tchnvkng
Author by

tchnvkng

Updated on July 21, 2022

Comments

  • tchnvkng
    tchnvkng almost 2 years

    I'm trying to learn some swift. I programmatically add labels. I want to change their properties later.

    the viewwithtag method returns a UIView, how to I access my UILabel from this?

    cheers

    • Andrey Chernukha
      Andrey Chernukha almost 10 years
      isn't UILabel an UIView? think about it
    • tchnvkng
      tchnvkng almost 10 years
      It is answered by Adam, Midhun, and iPatel.
  • Konrad77
    Konrad77 almost 10 years
    "var theLabel : UILabel = self.view.viewWithTag(123) as? UILabel" Shouldn't it be using ? as you can't be sure viewWithTag is not returning nil?
  • Adam
    Adam almost 10 years
    @Konrad77 well spotted. I have edited the answer
  • Toseef Khilji
    Toseef Khilji over 9 years
    It gives error, 'UILabel?' does not have a member named 'text'
  • Toseef Khilji
    Toseef Khilji over 9 years
    it gives fatal error: unexpectedly found nil while unwrapping an Optional value . i am using Xcode 6.1
  • Adam
    Adam over 9 years
    @Virussmca read about optionals here.
  • UGandhi
    UGandhi about 6 years
    it gives fatal error: unexpectedly found nil while unwrapping an Optional value . i am using Xcode 9.1
  • Adam
    Adam about 6 years
    @Coder Impossible to get that error using the code from my answer. It uses conditional unwrapping to prevent that exact error.