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;
Related videos on Youtube
Author by
tchnvkng
Updated on July 21, 2022Comments
-
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 almost 10 yearsisn't UILabel an UIView? think about it
-
tchnvkng almost 10 yearsIt is answered by Adam, Midhun, and iPatel.
-
-
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 almost 10 years@Konrad77 well spotted. I have edited the answer
-
Toseef Khilji over 9 yearsIt gives error,
'UILabel?' does not have a member named 'text'
-
Toseef Khilji over 9 yearsit gives
fatal error: unexpectedly found nil while unwrapping an Optional value
. i am using Xcode 6.1 -
Adam over 9 years@Virussmca read about optionals here.
-
UGandhi about 6 yearsit gives fatal error: unexpectedly found nil while unwrapping an Optional value . i am using Xcode 9.1
-
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.