Subview is childview which is added on any view. In iOS, UIView class is an object that manages the content for a rectangular area on the screen. UIView class contains the property var subviews: [UIView]
subviews
property to retrieve the subviews associated with your custom view hierarchies.To access the subviews, we need to change the behaviour a little bit. In our FirstApp, when you click on a Change Background button, it only change the background colour of our top-level view to light gray.
To retrieve all the labels and change the text colour, then we will need to use the subViews
property of view, and view is an instance of UIView.
@IBAction func changeBackground(_ sender: Any) {
view.backgroundColor = UIColor.lightGray
let subViews = view.subviews
for eachView in subViews {
if eachView is UILabel {
let currentLabel = eachView as! UILabel
currentLabel.textColor = UIColor.green
}
}
}
In this code the first line is
let subViews = view.subviews
for eachView in subViews {
if eachView is UILabel {
let currentLabel = eachView as! UILabel
currentLabel.textColor = UIColor.white
}
}
is
keyword.currentLabel
.Now we can change the text colour of a label using the textColor
property
currentLabel.textColor = UIColor.white`
Let's run your application and click on the Change Background button, and you will see that with background the colour of label text also changed when the button is clicked.