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.
- Now let's say we also want to change the text colour of all the label to a lighter colour to add some contrast on the dark background. - If you are from programming backgrounds, you might think that when you drag and drop a label or a button or anything else onto a storyboard in Xcode. - Then it will probably generating some unique identifier for each control. - And then you can just use those unique identifier in your Swift code to change the text of button or change the colour label. - That is not the case in iOS, here we have only the top-level container view object which was already configured in the standard Xcode iOS project template with the name view.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.